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

限于喜欢 提交于 2019-12-25 12:44:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!