Home > Enterprise >  How I can add key/value to the object in object? [closed]
How I can add key/value to the object in object? [closed]

Time:09-22

I have such array with objects:

[
  {age: 20, data: {money: 20}},
  {age: 30, data: {money: 30}},
  {age: 40, data: {money: 40}}
]

How can I add to every object the filed id to the object data? Id can be the same in every object.

Expected result:

{ageL 20, data: {money: 20, id: 1}}

CodePudding user response:

let myArray = [
  {age: 20, data: {money: 20}},
  {age: 30, data: {money: 30}},
  {age: 40, data: {money: 40}}
]
let myID = [
  1,
  2,
  3
]

myArray.map((obj, index) => {
  obj.data['id'] = myID[index]
})

console.log(myArray);

  • Related