Is it possible to remove spaces from a property name inside a reduction function?

I came up with the following way to reduce my data:

data = [{ id: 99991, name: "NoData1", title: "No Data" },
        { id: 99992, name: "NoData2", title: "No Data" },
        { id: 99993, name: "NoData3", title: "No Data" }];


var dataMapName = data.reduce((rv, v) => {
    rv[v.name] = v;
    return rv;
}, {}) : null

Now, if I want to access id, I can enter the following:

var NoData1Id = dataMapName['NoData1'].id

or

var NoData1Id = dataMapName.NoData1.id

However, some of my data has spaces in the name, for example:

data = [{ id: 99991, name: "NoData1", title: "No Data" },
        { id: 99992, name: "NoData2", title: "No Data" },
        { id: 99993, name: "NoData3", title: "No Data" },
        { id: 99994, name: "NoData 4", title: "No Data" },
];

Is there a way to change my function to first remove spaces from the name during shortening so that I can still enter:

var NoData4Id = dataMapName.NoData4.id
+4
source share
3 answers

Well then just replace the space with an empty string.

var dataMapName = data.reduce((rv, v) => {
                     rv[v.name.replace(' ', '')] = v;
                     return rv;
                  }, {}) : null

and another option is to use the data as is, just make sure that you use the parenthesis notation.

var NoData4Id = dataMapName.["NoData 4"].id
+1
source

You can use regex to remove all spaces from a name.

\s , , .. g .

rv[v.name.replace(/\s/g, '')] = v;

+2

You can change the card key during insertion:

data = [{ id: 99991, name: "NoData1", title: "No Data" },
        { id: 99992, name: "NoData 2", title: "No Data" },
        { id: 99993, name: "NoData3", title: "No Data" }];

var dataMapName = data.reduce((rv, v) => {
                     var vName = v.name.replace(/\s/g,'');
                     rv[vName] = v;
                     return rv;
                  }, {}) : null
0
source

Source: https://habr.com/ru/post/1607626/


All Articles