简体   繁体   中英

adding key to all values in an already existing javascript array

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM