Javascript string array to object [duplicate]

How do I convert a string array:

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

into an object like this?

var names = [
    {name:"Saab"},
    {name:"Michael"},
    {name:"Lanny"}
];

Answers:

Answer

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 }))
Answer

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

Answer

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}
});
Answer

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}});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.