Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:"Bob"},
    {name:"Michael"},
    {name:"Lanny"}
];
like image 644
Elron Avatar asked Mar 21 '18 23:03

Elron


People also ask

How do you remove duplicates from array of objects?

Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you duplicate items in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

Can array have duplicate values JavaScript?

If the lengths are not the same, it must follow that the array contained duplicate values! If the length of the Set and the array are not the same this function will return true , indicating that the array did contain duplicates.


2 Answers

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 }))
like image 108
Phil Avatar answered Oct 03 '22 09:10

Phil


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

like image 23
alejandro estrada Avatar answered Oct 03 '22 09:10

alejandro estrada