0

I have a function as below which finds a particular element in an array of objects and updates it:

async update(id, attrs){
    const records = await this.getAll();
    const record = records.find(record => record.id === id);
    Object.assign(record, attrs);
    await this.writeAll(records);

}

I was surprised to understand the find method returns a reference to the matching element in the records array whereas I was expecting that the record variable would just contain the value and changing it would not cause the original records array to get updated.

So my question is, what if I just want to retrieve the value from an object array but not a reference to the actual element? that is, I need to be able to update the returned value without mutating the original array.

theju112t
  • 37
  • 9
  • To have deep copy mechanism use Spread operator const record = { ...records.find(record => record.id === id) }; **OR** JSON.parse(JSON.stringify()) method const record = JSON.parse(JSON.stringify(records.find(record => record.id === id))); – Nitheesh Sep 24 '21 at 03:01
  • `find` returns whatever value is in the array. If it's an object, you get that object, it doesn't make a clone of it. – Bergi Sep 24 '21 at 03:01
  • @Bergi so what should i do? – theju112t Sep 24 '21 at 03:02
  • @theju112t Don't use `Object.assign` with the found `record` as the target. Copy the properties into a new object: `writeAll(Object.assign({}, record, attrs))`. Or see any other way to clone the object. – Bergi Sep 24 '21 at 03:04

0 Answers0