Adding new keys and a set of values to an already existing array in javascript

Viewed 45

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?

3 Answers

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

Related