3

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 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.