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
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"}]
PS please add a condition for case if arrays will have different length
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();
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.