Search code examples
javascriptarraysobjectpass-by-reference

Replace values in array of object with values from another array in JavaScript


This should be a small task, but could not figure it out. I've an array of objects named 'A'

A = [{x:a,y:10},{x:b,y:5},{x:c,y:50}]

and an array named 'B'

B = ['2022-06-15','2022-06-16','2022-06-17']

Need to replace the value of x in A with the values of B

Expected output C

C = [{x:'2022-06-15',y:10},{x:'2022-06-16',y:5},{x:'2022-06-17',y:50}]

I'm using a for loop but it changes the original array 'A' (since JS arrays are pass-by-reference)

const D = A; // or D = [...A]

for (let i = 0; i < D.length; i++) {
        D[i].x = B[i];
}
console.log(A);
console.log(D);

Solution

  • Don't make D a copy of A. Loop over A and make copies of each object with the x property replaced.

    const D = A.map((el, i) => ({...el, x: B[i]}));