-4

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

drew schmaltz
  • 1,584
  • 4
  • 19
  • 29
  • 1
    what did you try so far? – omarjmh Jul 13 '16 at 01:38
  • 2
    seriously this is not a homework for free service.. – webdeb Jul 13 '16 at 01:43
  • webdev & JordanHendrix, actually doing this is extremely easy. It's also ugly (see below). I guess I was really just trying to ask if underscore had a method for it or if some clever combination of methods would clean up the task. No homework here webdev. – drew schmaltz Jul 13 '16 at 02:10
  • ok JordanHendrix posted exactly the type of answer I was looking for in the comments below. I'm sorry I didn't include a really crappy way of accomplishing it before asking for a clever way. I need to study up on .map() because it seems to be the common deuglifier. – drew schmaltz Jul 13 '16 at 02:14
  • You all down voted the crap out of this, but go ahead and watch how useful this becomes to people in the future. People of the future, you're welcome. – drew schmaltz Jul 13 '16 at 02:17
  • not really, there are multiple duplicates with positive votes...heres one: http://stackoverflow.com/questions/12199051/merge-two-arrays-of-keys-and-values-to-an-object-using-underscore – omarjmh Jul 13 '16 at 14:00
  • That's one array as keys and one as values. That's different. – drew schmaltz Jul 14 '16 at 00:10

1 Answers1

0

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);
Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70