问题
I have an array:
var countries = ['Austria', 'America', 'Australia'];
I know you can turn that into an object with Underscore.js like this:
_.object(['name', 'name2', 'name3'], countries));
How can I turn the array into an array of objects that looks like this?
var countriesObject = [
{ name: 'Austria' },
{ name: 'America' },
{ name: 'Australia' }
];
(with all the keys named name
).
回答1:
No need to use Underscore.js for that. You can do it with plain javascript:
var new_arr = [];
countries.forEach(function(country) {
var new_obj = {};
new_obj.name = country;
new_arr.push(new_obj);
});
console.table(new_arr);
回答2:
var countriesObject = _.map (countries,function (country){
return {
name: country
}
}
来源:https://stackoverflow.com/questions/22280580/turning-an-array-into-an-array-of-objects-with-underscore-js