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?

1
  • You're not changing item in the code you posted. Consider posting all relevant code. Commented Feb 2, 2019 at 10:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

looks like also find function is doing the same: if i do pippo.id = 100 then also the maledettoArray item will have 100
Yes because objects are passed by reference so if you want to modify the result you need to create a copy.
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.
and in case of nested object?
Use lodash cloneDeep or see this answer stackoverflow.com/questions/122102/…
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.