drew schmaltz drew schmaltz - 4 months ago 17
Javascript Question

Merge 2 arrays using 2 different keys

If you have 2 arrays

var number = [1, 2, 3];
var color = ['red', 'white', 'blue'];


How can you create an object that looks like this:

var combined = [
{
number: 1,
color: 'red'
},
{
number: 2,
color: 'white'
},
{
number: 3,
color: 'blue'
},
];


Bonus points for using underscore.js

Answer

Using underscore,

var number = [1, 2, 3];
var color = ['red', 'white', 'blue'];
var combined = _.map(number, function(num, key) {
    return {
        number: num,
        color: color[key]
    }
});

console.log(combined);