0

I have any array of objects like this

let myObj=[{a:'CR',showMe: true},{a:'PY'}];

Now I'm trying to find the object which has a as CR and showMe as true and want to change the a value.

let findObj = myObj.filter(i=> i.a == 'CR' && i.showMe);

findObj.map(ele => ele['a'] = "PS"); 

When I'm trying to console myObj,value of a in myObj is changed along with findObj.

I don't want myObj to be changed.

What is causing the issue, could someone help?

0stone0
  • 34,288
  • 4
  • 39
  • 64
valli
  • 103
  • 2
  • 11
  • 1
    You need to deep clone `myObj` because currently, `findObj` is an array of the same elements. A quick and dirty fix is `let findObj = JSON.parse(JSON.stringify(myObj)).filter(i=> i.a == 'CR' && i.showMe);` (also, you should use `.forEach` instead of `.map` when just want to iterate over the objects) –  May 27 '21 at 15:03
  • Duplicate: [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) –  May 27 '21 at 15:08
  • 'I don't want myObj to be changed.' Do you only want the 'changed' object to be in the result? Or do you also expect `{a:'PY'}` to be in the result array? – 0stone0 May 27 '21 at 15:10

2 Answers2

1

You need to (shallow) clone the objects in findObj so that modifying them doesn't modify the objects in myObj

let myObj=[{a:'CR',showMe: true},{a:'PY'}];
let findObj = myObj.filter(i=> i.a == 'CR' && i.showMe);

findObj = findObj.map(obj => ({...obj, a: 'PS'})); 

console.log(myObj);
console.log(findObj);

Other comments & answers suggest suggest using JSON.parse(JSON.strinfigy(obj)) to deep clone objects, but this is lossy; e.g. it loses types and methods. In your case, your objects are 1 level deep (i.e. don't contain nested arrays or objects), so a shallow clone is sufficient. The spread operator {...obj} is the simplest way to shallow clone objects. Object.assign({}, obj) is another more verbose alternative.

junvar
  • 11,151
  • 2
  • 30
  • 46
0
let myObj = [{
  a: 'CR',
  showMe: true
}, {
  a: "FF",
  showMe: true
}];

let result = [];
myObj.filter(i=> {
 let item = Object.assign({}, i);
 return item.a == 'CR' && item.showMe && result.push(item)
});
result.map(ele => { ele['a'] = "PS"}); 
console.log({myObj, result});