Home > Back-end >  Replace array of objects with new object
Replace array of objects with new object

Time:02-03

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 :(

CodePudding user response:

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));

CodePudding user response:

You can use the map() function:

const updatedArray = sampleArray.map(item => item.id === 'hotel' ? {...item, id: 'hotel2'} : item); 

CodePudding user response:

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; }

  •  Tags:  
  • Related