简体   繁体   中英

How to modify an array of object and push in JavaScript?

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?

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=> ia == '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; eg it loses types and methods. In your case, your objects are 1 level deep (ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM