简体   繁体   中英

Turning an array into an array of objects with Underscore.js?

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 ).

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);
var countriesObject = _.map (countries,function (country){
    return {
            name: country
     }
 }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM