0

For example, let's say I have the following:

let data = [{name: "Bob"}, {name: "Alice"}]
let numArr = [12, 34]

I'd like this as the result:

let newData = [{name: "Bob", number: 12}, {name: "Alice", number: 34}]

2 Answers 2

3

Using Array#map:

const 
  data = [{name: "Bob"}, {name: "Alice"}],
  numArr = [12, 34];

const newData = data.map((e, i) => ({ ...e, number: numArr[i] }));

console.log(newData);

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

Comments

1

You can use Symbol.iterator and forEach.

let data = [{name: "Bob"}, {name: "Alice"}];
let numArr = [12, 34];

ns=numArr[Symbol.iterator]();
data.forEach((d)=>d.number=ns.next().value);

document.write(JSON.stringify(data));

You need to define the iterated array outside of the forEach loop, otherwise the definition is re-initiated with every pass, and returns the same value each time.

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.