Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 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 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...