Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading