Tengo una matriz de objetos y me gustaría reemplazar un objeto con un nuevo objeto que tenga una identificación específica. Mi objetivo es reemplazar/eliminar el objeto donde id === 'hotel' con un objeto completamente nuevo y mantener el mismo índice.
Ejemplo / Código actual
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 :(No necesita la lógica de empalme elegante. Simplemente configure el elemento de matriz y olvídelo.
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));Puedes usar la función map() :
const updatedArray = sampleArray.map(item => item.id === 'hotel' ? {...item, id: 'hotel2'} : item);Otra forma, reemplazando un elemento de matriz por índice
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; }