adding key to all values in an already existing javascript array

Viewed 36

I have this array:

myArray=['joe', 'sarah', 'jack', 'steph']

I want to add the key name to it so it becomes like this:

myArray=[{name: 'joe'}, {name: 'sarah'}, {name: 'jack'}, {name: 'steph'}]

I have tried:

myArray.map(o => ({ name: o, ...o }));

but it doesn't work. How can I do it?

1 Answers

Just remove the spread syntax which is spreading the characters of the string into the object.

myArray=['joe', 'sarah', 'jack', 'steph']
console.log(myArray.map(o => ({ name: o})));

Related