Home > front end >  How could I go about appending array elements to an array of objects in Javascript?
How could I go about appending array elements to an array of objects in Javascript?

Time:12-29

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related