Home > Back-end >  Copy original array with empty values
Copy original array with empty values

Time:02-13

I have the following array:

arr1 = [{Name: "John", Email: "[email protected]", Age: "29"}, {Name: "Emma", Email: "[email protected]", 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: "[email protected]", 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.

CodePudding user response:

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

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

Here's your code refactored to work as intended.

arr1 = [{Name: "John", Email: "[email protected]", Age: "29"}, {Name: "Emma", Email: "[email protected]", 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: "[email protected]", Age: "25"}]
console.log([arr2]) //returns [{Name: "", Email: "", Age: ""}]

CodePudding user response:

let arr1 = [{Name: "John", Email: "[email protected]", Age: "29"}, {Name: "Emma", Email: "[email protected]", Age: "25"}]
let arr2 = {...arr1[0]}

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

console.log(arr1)  
console.log(arr2)

CodePudding user response:

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>

  • Related