简体   繁体   中英

Change index in array.map

I have a variable of the form:

var data=[
{
    start:22,
    end: 8
},
{
    start:60,
    end: 43       
},
{
    start: 35,
    end: 55
},
{
    start:25,
    end:40
}
];

I want to map it to look like this

var newData = { 22:8, 60:43, 35:55, 25:40};

Is this possible? I mainly just want to use the start numbers as a key to access the end numbers without using search. I have tried to do this:

 var mapData = data.map(function(data){
  var x = {};
  x[data.start]=data.end;
  return x;
});

but it gives: 0 : {22: 8} 1 : {60: 43} 2 : {35: 55} 3 : {25: 40} which means i have to use 0, 1,2, 3 as indices.

Only Array#map does not work in this case, because without post processing, you get a single array with objects. You need to combine all objects into a single object.

With Object.assign and spread syntax ... , you get a single array with all properties from the objects in the array.

 var data = [{ start: 22, end: 8 }, { start: 60, end: 43 }, { start: 35, end: 55 }, { start: 25, end: 40 }], result = Object.assign(...data.map(({ start, end }) => ({ [start]: end }))); console.log(result); 

You can use array.reduce:

 var data=[ { start:22, end: 8 }, { start:60, end: 43 }, { start: 35, end: 55 }, { start:25, end:40 } ]; var res = data.reduce((m, o) => { m[o.start] = o.end; return m; }, {}); console.log(res); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM