10

How do I convert a string array:

var names = [
    "Bob",
    "Michael",
    "Lanny"
];

into an object like this?

var names = [
    {name:"Bob"},
    {name:"Michael"},
    {name:"Lanny"}
];
Elron
  • 1,235
  • 1
  • 13
  • 26

4 Answers4

27

Super simple Array.prototype.map() job

names.map(name => ({ name }))

That is... map each entry (name) to an object with key "name" and value name.

var names = [
    "Bob",
    "Michael",
    "Lanny"
];

console.info(names.map(name => ({ name })))

Silly me, I forgot the most important part

names.map(name => name === 'Bob' ? 'Saab' : name)
     .map(name => ({ name }))
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 2
    Haha thanks, Phil :) That "Saab" was a spelling mistake, but I loved that you related to it and gave an answer to that too. – Elron May 08 '20 at 17:15
3

Use the Array.map() function to map the array to objects. The map() function will iterate through the array and return a new array holding the result of executing the function on each element in the original array. Eg:

names = names.map(function(ele){return {"name":ele}});
webnetweaver
  • 192
  • 8
2

You can do this too:

var names = [
"Bob",
"Michael",
"Lanny"
];

var objNames = []

names.forEach(name => {
  objNames.push({
    name
  })
})

Using ES6 you can set name and it is equal to name: name

2

you can use the map function. In general, list.map(f) will produce a new list where each element at position i is the result of applying f to the element at the same position in the original list. For example:

names.map(function(s) { 
    return {name: s}
});
Alex Pinto
  • 162
  • 1
  • 7