Trevor Behnke
Trevor Behnke

Reputation: 45

How could I go about appending array elements to an array of objects in Javascript?

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}]

Upvotes: 0

Views: 45

Answers (2)

JMP
JMP

Reputation: 4467

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.

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28404

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

Upvotes: 3

Related Questions