0

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);
3
  • const D = [...A] to shallow copy the array. There is also const D = A.slice();, and many more methods to shallow copy arrays. Commented Sep 6, 2022 at 19:39
  • @kelly He needs to deep-copy it. Commented Sep 6, 2022 at 19:40
  • Oh, yeah I got D[i].x and B[i] switched around Commented Sep 6, 2022 at 19:41

2 Answers 2

1

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]}));
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.