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

249
Visualizações
Get confusion while using "Array. Map" method in JavaScript

My code is :

let obj1 = [
    { city: 'Tokyo', country: 'Japan' },
    { city: 'Bangkok', country: 'Thailand'}
];
function myFunc(arr, key, value){
    let newArr = arr.map((e)=>{
       let obj = e;
       obj[key] = value;
       return obj;
    })
    return newArr
}

console.log(myFunc(obj1, 'continent', 'Asia'));
console.log(obj1);

I don't want to mutate the "obj1" array. That's why I'm using Array.map method. But it still changing the original Array. Does anyone know why this happening? Where I made the mistake?

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

0

You could take a new object and spread the old one.

function myFunc(arr, key, value){
    return  arr.map(e => ({ ...e, [key]: value }));
}

let obj1 = [{ city: 'Tokyo', country: 'Japan' }, { city: 'Bangkok', country: 'Thailand'}];

console.log(myFunc(obj1, 'continent', 'Asia'));
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

You thought that using the equal operator will copy each object in array so you don't mutate the object

let obj = e;

but what you have in code is another reference to the same item(s) in array.

map itself is not a gurantee you have immutable data structure, you have to correctly copy the data, for objects in js you can use either Object.assign or the spread operater

  let obj = { ...e };
  // or
  let obj = Object.assign({}, e);
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