简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM