8

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
  • 971
  • 1
  • 10
  • 20

4 Answers4

24

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
  • 141,914
  • 21
  • 225
  • 223
  • 1
    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
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

1

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
  • 152
  • 1
  • 7
1

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
  • 172
  • 8