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
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.
You're passing by reference instead of copying the array.
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: ""}]
let arr1 = [{Name: "John", Email: "john@example.com", Age: "29"}, {Name: "Emma", Email: "emma@example.com", Age: "25"}]
let arr2 = {...arr1[0]}
for (let i in arr2) {
arr2[i] = ""
}
console.log(arr1)
console.log(arr2)
Just Simple replace the values using for loop or in the way you want to change it.
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
// Update the name value
myDog.name = "Happy Coder";
document.getElementById("p1").innerHTML = Object.values(myDog);
<div id='p1'></div>