Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda