Search code examples
javascriptarray-map

How to update an array of objects with data taken from the corresponding elements of another same-size array?


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?


Solution

  • 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.