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

117
Vistas
Replace array of objects with new object

I have an array of objects and I would like to replace an object with a new object that has a specific id. My goal is to replace/remove the object where id === 'hotel' with an entirely new object and keep the same index.

Example / Current Code

const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]

const index = sampleArray.findIndex((obj) => obj.id === 'hotel1') // find index
sampleArray = sampleArray.splice(index, 0) // remove object at this index
sampleArray.splice(index, 0, { id: 'hotel2' }) // attempt to replace with new object ... not working :(
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You don't need the fancy splice logic. Just set the array element and forget it.

const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]

const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
sampleArray[index] = { id: 'hotel2' }; // replace with new object ... working :)

console.log(JSON.stringify(sampleArray));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the map() function:

const updatedArray = sampleArray.map(item => item.id === 'hotel' ? {...item, id: 'hotel2'} : item); 
about 4 years ago · Juan Pablo Isaza Denunciar

0

Another way, replacing an array element by index

const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]

const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
Object.assign(sampleArray, { [index]: { id: 'hotel2' } }); // replace with new object


console.log(sampleArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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