Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
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

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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: ""}]

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda