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

Copy original array with empty values

I have the following array:

arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]

How can I get this array as:

arr2 = [{Name: "", Email: "", Age: ""}]

without mutating arr1

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

I have tried doing:

let arr2 = arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log(arr2) //returns [{Name: "", Email: "", Age: ""}]

but this mutates arr1[0] with empty values as well

I have searched a lot of questions on SO, but couldn’t get anything that would set all the values empty.

>Solution :

You’re passing by reference instead of copying the array.

https://dmitripavlutin.com/value-vs-reference-javascript/#:~:text=In%20JavaScript%2C%20you%20can%20pass,by%20reference%20when%20assigning%20objects.

Here’s your code refactored to work as intended.

arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
let arr2 = {...arr1[0]} // make a copy of arr1[0]

for (let i in arr2) {
    arr2[i] = ""
}

console.log(arr1) //returns [{Name: "", Email: "", Age: ""}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
console.log([arr2]) //returns [{Name: "", Email: "", Age: ""}]
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