seyet
seyet

Reputation: 1150

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

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?

Upvotes: 3

Views: 49

Answers (3)

Unmitigated
Unmitigated

Reputation: 89234

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

Upvotes: 2

HenryDev
HenryDev

Reputation: 4953

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

Upvotes: 1

hgb123
hgb123

Reputation: 14891

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)

Upvotes: 1

Related Questions