1

I have some information collected by array, like:

var names = ["Jack", "Marry", "Bob"]
var cars = ["Audi", "BMW", "Volvo"]

I want these info combine to object like collection, like:

[{name:"Jack", car: "Audi"}, {name: "Marry", car:"BMW"}, {name:"Bob", car:"Volvo"}]

I can do this by some steps:

var combine = _.zip(names, cars)
var collection= _.map(combine, function(info){
                      return _.object(["name", "car"], info);
                     });

Is there other way to make code look better? Thanks

2 Answers 2

1

How about es5 array.map()?

var names = ["Jack", "Marry", "Bob"]
var cars = ["Audi", "BMW", "Volvo"]

var result = names.map(function(val, key){
 return {name: val, car: cars[key]}
})

console.log(result); //[{car: "Audi", name: "Jack"}, {car: "BMW", name: "Marry"}, {car: "Volvo", name: "Bob"}]

P.S. please add a condition for case if arrays will have different length

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to stick with Underscore, you could combine your two steps using chaining:

var result = _(names).chain()
                     .zip(cars)
                     .map(function(a) { return { name: a[0], car: a[1] } })
                     .value();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.