0

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

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3
var countriesObject = _.map (countries,function (country){
    return {
            name: country
     }
 }

1 Comment

missing a ) at the end.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.