On the problem of deep copy and shallow copy of JavaScript object array

what you want to achieve

traverses an array whose elements are objects and a tree structure. If the PID of an array element is a value, set the checked attribute of that element to true

for(var i=0;i<initdata.length;iPP){
    if($.inArray(initdata[i].id, subjectids) > -1){
         initdata[i].checked=true;
         if(parseInt(initdata[i].isleaf) === 0){
              initdata = checkNode(initdata,initdata[i].id);
         }
    }else{
         initdata[i].checked=false;
    }
}
function checkNode(initdata,pid){
        for(var j=0;j<initdata.length;jPP){
            if(parseInt(initdata[j].pid) === parseInt(pid)){
                initdata[j].checked = true;
            }
        }
        return initdata;
    }

the data structure is as follows

0:
checked: true
id: "5001"
isleaf: "0"
level: "1"
name: ""
open: true
pid: "5"
__proto__: Object
1:
checked: false
id: "500101"
isleaf: "1"
level: "2"
name: ""
open: true
pid: "5001"
__proto__: Object
2:
checked: false
id: "500102"
isleaf: "1"
level: "2"
name: ""
open: true
pid: "5001"
__proto__: Object
3:
checked: true
id: "5051"
isleaf: "1"
level: "1"
name: ""
open: true
pid: "5"
__proto__: Object

directly manipulate the final result of initdata,. Checked is not set to true [No data problem]

I hope God will give me some advice. I probably know that it is the problem of deep copy and shallow copy of JS, but I don"t know how to solve it.

Jan.23,2022

function checkNode (initdata, pid) {
  const init = initdata.find((init) => init.pid === pid);
  init.checked = true;
}

just remove the else code. Originally, in the first time of the for cycle, all four pieces of data were changed to true, but then the second piece of data was judged as false, by if ($.inArray (initdata [I] .id, subjectids) >-1), so the checked value was changed to false. by else. The value of the data itself is false, so removing this will not only meet the demand, but also solve the problem

Menu