简体   繁体   English

更改array.map中的索引

[英]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. 但它给出:0:{22:8} 1:{60:43} 2:{35:55} 3:{25:40}这意味着我必须使用0、1、2、3作为索引。

Only Array#map does not work in this case, because without post processing, you get a single array with objects. 在这种情况下,只有Array#map不起作用,因为如果不进行后期处理,您将获得带有对象的单个数组。 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. 使用Object.assignspread语法... ,您可以从数组中的对象获得具有所有属性的单个数组。

 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: 您可以使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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