Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!