Home > Back-end >  Replace values in array of object with values from another array in JavaScript
Replace values in array of object with values from another array in JavaScript

Time:09-07

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);

CodePudding user response:

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]}));

CodePudding user response:

Try this, it will create a deep copy of A into D, so that when you change D it will not change A.

const D = JSON.parse(JSON.stringify(A));;

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

CodePudding user response:

You can do it with .map() method

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

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

x represents each element inside your A array and i the index, that you will use to loop thru your second array B

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

console.log(C);
  • Related