Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

ecmascript 6 - ES6: Merge two arrays into an array of objects

I have two arrays that I want to merge together to one array of objects...

The first array is of dates (strings):

let metrodates = [
 "2008-01",
 "2008-02",
 "2008-03",..ect
];

The second array is of numbers:

let figures = [
 0,
 0.555,
 0.293,..ect
]

I want to merge them to make an object like this (so the array items match up by their similar index):

let metrodata = [
   {data: 0, date: "2008-01"},
   {data: 0.555, date: "2008-02"},
   {data: 0.293, date: "2008-03"},..ect
];

So far I do this like so: I create an empty array and then loop through one of the first two arrays to get the index number (the first two arrays are the same length)... But is there an easier way (in ES6)?

  let metrodata = [];

  for(let index in metrodates){
     metrodata.push({data: figures[index], date: metrodates[index]});
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest way is probably to use map and the index provided to the callback

let metrodates = [
  "2008-01",
  "2008-02",
  "2008-03"
];

let figures = [
  0,
  0.555,
  0.293
];

let output = metrodates.map((date,i) => ({date, data: figures[i]}));

console.log(output);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...