0

I've a react application, and i've found a bug where i'm filtering an array for searching the current item the user has selected and then i'm going to do stuff with it...but, didn't know that filter function return a reference to the array's item, so, every change i made to the selected item i'm doing the same to the prop array.

const pippo = maledettoArray.filter(item => item.id === idInfame)[0];

How can i filter the prop array to get the specific item without changing it?

claud.io
  • 1,523
  • 3
  • 15
  • 30

2 Answers2

2

You can use find method instead of filter which returns first match and exits the loop.

const pippo = maledettoArray.find(item => item.id === idInfame)

To create shallow copy of the object you can use Object.assign or spread syntax.

const clone = {...pipo}

If you want to create deep copy of the nested object then you could use Lodash _.cloneDeep(value) method.

Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • looks like also find function is doing the same: if i do pippo.id = 100 then also the maledettoArray item will have 100 – claud.io Feb 02 '19 at 10:47
  • Yes because objects are passed by reference so if you want to modify the result you need to create a copy. – Nenad Vracar Feb 02 '19 at 10:49
  • 1
    Note that {...obj} creates just a shallow copy, so if you have nested objects and modify some of its properties you still change the original. – Nenad Vracar Feb 02 '19 at 10:51
  • and in case of nested object? – claud.io Feb 02 '19 at 11:16
  • Use lodash cloneDeep or see this answer https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Nenad Vracar Feb 02 '19 at 11:17
2

First of all, I would recommend you use the find function instead of filter to avoid the empty array return and undefined at [0]

Secondly, yes, the object reference would be returned. To avoid this, you can use Object.assign({}, originalObject) or using the spread syntax {...originalObject} . A potential problem would be with nested objects which could still be a problem. Probably this article can help you in such case https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25