Search code examples
javascriptarraysjavascript-objects

Adding items to an object array from another array


I have an array like this:

data = [1, 2, 3, 4, 5]

and I have an array of objects like this:

obj = [{"Name":"ABC","Age":25,"Gender":"M"},
       {"Name":"DEF","Age":32,"Gender":"F"},
       {"Name":"PQR","Age":30,"Gender":"F"},
       {"Name":"XYZ","Age":30,"Gender":"F"}]

I need to push each element of the data array into each object of the array. My expected output is this:

obj = [{"Name":"ABC","Age":25,"Gender":"M", "Data":1}, 
       {"Name":"DEF","Age":32,"Gender":"F", "Data":2}, 
       {"Name":"PQR","Age":30,"Gender":"F", "Data":3}, 
       {"Name":"XYZ","Age":30,"Gender":"F", "Data":4}]

I tried like this:

for(let i = 0; i<data.length; i++){
   obj.push({data:data[i])
}

But that gave an incorrect result like this:

obj = [{"Name":"ABC","Age":25,"Gender":"M"},
       {"Name":"DEF","Age":32,"Gender":"F"}, 
       {"Name":"PQR","Age":30,"Gender":"F"},
       {"Name":"XYZ","Age":30,"Gender":"F"}, 
       {"Data":1},{"Data":2},{"Data":3},{"Data":4}]

I understand that this is because I am not iterating through array of object before pushing the items into it. But I am unable to iterate through data as well as obj together. Please help me solve the issue. Thanks in advance.


Solution

  • Given that the length of the 2 arrays are the same:

    for (let i = 0; i < data.length; i++) {
        obj[i].Data = data[i];
    }