11

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"}
];
5
  • 10
    Where did "Saab" come from? Commented Mar 21, 2018 at 23:40
  • You might loop over the array and assign new values to elements like names[i] = {name: names[i]}. Commented Mar 21, 2018 at 23:41
  • @PeterB Thanks for finding the duplicate. Adding it to "the list" :) Commented Mar 21, 2018 at 23:48
  • @Phil—not me, I just seconded Peter B's dupe. Commented Mar 21, 2018 at 23:49
  • 1
    @Phil right, there's no "Saab", sorry, I fixed that Commented May 8, 2020 at 17:13

4 Answers 4

30

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

1 Comment

Haha thanks, Phil :) That "Saab" was a spelling mistake, but I loved that you related to it and gave an answer to that too.
4

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.