-1

Say I have an array of objects as follows:

data = [
{
 "id":34
},
{
 "id":35
},
{
 "id":36
},
{
 "id":37
}
]

and another array as follows:

myNumberArray  = [1,2,3,4]

They might be much larger, but the number of elements in both arrays will always be the same. I want to modify each element of data by adding a number attribute, assigning it the value from the corresponding element of myNumberArray.

When done, data will look as follows:

data = [
{
 "number":1,
 "id":34
},
{
 "number":2,
 "id":35
},
{
 "number":3,
 "id":36
},
{
 "number":4,
 "id":37
}
]

How can I do this?

Inigo
  • 12,186
  • 5
  • 41
  • 70
Rahul
  • 29
  • 5

4 Answers4

1
myNumberArray  = [1,2,3,4]

data = [
 {
  "id":34
 },
 {
  "id":35
 },
 {
  "id":36
 },
 {
  "id":37
 }
]

data.forEach((elem, index)=>{
  data[index]["number"]=myNumberArray[index];
})

console.log(data);

This should solve your problem.

Explanation:

I used forEach to iterate over the data array, forEach accepts two parameters, the current value at an index, and the value.

Since, yours is a one-to-one mapping, we are using the current index to access the value at the same index in myNumberArray and assigning that new value in data for number key.

Abhishek Jain
  • 630
  • 6
  • 26
0

Try the following solution:

let myNumberArray  = [1,2,3,4];

let data = [
{
 "id":34
},
{
 "id":35
},
{
 "id":36
},
{
 "id":37
}
];

const updatedArray = data.map((item,index)=> {
  return {
    ...item,
    "number":myNumberArray[index]
  }
});

console.log(updatedArray);
Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
0

let myNumberArray  = [1,2,3,4]

let data = [
{
 "id":34
},
{
 "id":35
},
{
 "id":36
},
{
 "id":37
}
]


data = data.map( (x, i) => ({ number: myNumberArray[i], id: x.id}) )


console.log(data)
Inigo
  • 12,186
  • 5
  • 41
  • 70
-1
for (let i in myNumberArray) {
  Object.assign(data[i], {
    number: myNumberArray[i]
  })
}