简体   繁体   中英

Javascript, combine two array into a format

is it possible to turn two array into a specific format , because i need the specific format to create my D3 graph.

Actually, what i have , it's these two array,

date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"]
likes = [2,4,5]

and i want to turn into this format

[{ date: '...', likes: '...'},
 { date: '...', likes: '...'}]

You can do it in a simple way:

date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"];
likes = [2,4,5];
final = [];

if (date.length == likes.length)
  for (i = 0; i < dates.length; i++)
    final.push({
      date: dates[i],
      likes: likes[i]
    });

Also, checking both whether they are of same size, to make sure it should not go into an array index out of bound.

One way would be to use a simple for loop.

var result = [];
for (var i = 0, len = date.length; i < len; i++) {
  result.push({
    date: date[i],
    likes: likes[i]
  });
}

Note that this only works if the arrays are of the same length. If they aren't you could still get the maximum possible by taking the minimum of the two lengths.

var result = [];
var length = Math.min(date.length, likes.length);
for (var i = 0; i < length; i++) {
  result.push({
    date: date[i],
    like: likes[i]
  });
}

Assuming they have the same length you can use Array.prototype.map() :

var newArr = likes.map(function(item, index){
   return { date: dates[index], like: item };
});

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