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?

3
  • 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) Commented May 27, 2021 at 15:03
  • Duplicate: What is the most efficient way to deep clone an object in JavaScript? Commented May 27, 2021 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? Commented May 27, 2021 at 15:10

2 Answers 2

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.

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

Comments

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});

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.