I have this data:
myArray=['joe', 'sarah', 'jack', 'steph']
tempString = ' rogan'
I want to convert it to this:
myArray=[
{name: 'joe', value: 'joe rogan'},
{name: 'sarah', value: 'sarah rogan'},
{name: 'jack', value: 'jack rogan'},
{name: 'steph', value: 'steph rogan'}
]
I have tried:
myArray.map(o => ({ name: o.name }, { value: o.name + tempString });
but it doesn't work. How can I do it?
You want to return one object with both properties, so you should not be creating two separate object literals. In your case, the comma operator is causing only the last (second) one to be returned.
const myArray=['joe', 'sarah', 'jack', 'steph'] const tempString = ' rogan' const res = myArray.map((name)=>({name,value:name+tempString})); console.log(res);
Below snippet could help you
const myArray = ["joe", "sarah", "jack", "steph"] const tempString = " rogan" const res = myArray.map((name) => ({ name: name, value: name + tempString, })) console.log(res)
You can also use the forEach function to iterate through arrays:
const myArray = ["joe", "sarah", "jack", "steph"] const tempString = " rogan"; let newArray = []; myArray.forEach((name) => newArray.push({name, value: name + tempString})); console.log(newArray);
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.