Claus Claus - 1 month ago 5
Javascript Question

drilling down in a set of nested objects in JavaScript

I have 4 objects nested within each other. I am trying to change the value of the "chk" property in the inner most object of all the records. Each object has a variable number of properties.

The basic structure is like this

EMPLOYEE NAME
JOB#
PHASE
CODE
DAYSoFwEEK
CHK


I was trying to use some for in loops to get there like this

this.chkEmp = function(e)
{
/*e is an event listener which is triggered by a click on one of the check boxes. the id is the value of the outer most object*/
var i = e.target.id;

/*loop through jobs
this is where I get in trouble j is the job which is an object
so I think "this.recs[i][j]" is not a proper reference
*/
for ( var j in this.recs[i] )
{
/*loop through phase codes*/
for ( var p in this.recs[i][j] )
{
for ( var c in this.recs[i][j][p] )
{
this.recs[i][j][p][c].chk = e.target.checked;
}
}
}
};


How can I loop through all the data and change the value of chk from true to false?

Here is some sample data

"Last_Name, First_Name" Object { 85109={...}, 85665={...}, 85762={...}}
85109 Object { 60={...}}
85665 Object { 60={...}}
60 Object { 1={...}, 3={...}}
1 Object { 0=0, 1=0, 2=0, more...}
0 0
1 0
2 0
3 2.75
4 0
5 0
6 0
chk true
3 Object { 0=0, 1=0, 2=0, more...}
85762 Object { 60={...}}
60 Object { H={...}}
H Object { 0=0, 1=10.5, 2=10.75, more...}
0 0
1 10.5
2 10.75
3 5.75
4 0
5 0
6 0
chk true

Answer

Re-writing as follows (with more meaningful variable names) should make the program easier to reason about.

this.chkEmp = function (e) {
    /*e is an event listener which is triggered by a click on one of the check boxes.  the id is the value of the outer most object*/
    var i = e.target.id;

    /*loop through jobs
      this is where I get in trouble j is the job which is an object
      so I think "this.recs[i][j]" is not a proper reference
    */
    var recs = this.recs[i];
    var recsJ, recsJp, recsJpc;

    for (var j in recs) {
        recsJ = recs[j];
        /*loop through phase codes*/
        for (var p in recsJ) {
            recsJp = recsJ[p];
            for (var c in recsJp) {
                recsJpc = recsJp[c];
                recsJpc.chk = e.target.checked;
            }
        }
    }
};
Comments