javascript - 在 JavaScript 中深入研究一组嵌套对象

标签 javascript

我有 4 个相互嵌套的对象。我正在尝试更改所有记录的最内部对象中的“chk”属性的值。每个对象都有数量可变的属性。

基本结构是这样的

    EMPLOYEE NAME
      JOB#
        PHASE
           CODE
             DAYSoFwEEK
             CHK

我试图使用一些 for in 循环来达到这样的效果

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

如何循环遍历所有数据并将 chk 的值从 true 更改为 false?

这是一些示例数据

"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

最佳答案

按如下方式重写(使用更有意义的变量名称)应该会使程序更易于推理。

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

关于javascript - 在 JavaScript 中深入研究一组嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245256/

相关文章:

javascript - ajax 无效 json,为什么这是无效的 JSON?

javascript - 屏幕和窗口属性之间的区别?

javascript - flex 元素不包装在列方向 flex 盒中

javascript - 从 useReducer Hook 返回的状态是 "deep copy"还是 reducer 输出的引用?

javascript - NestJS无法解析服务mongodb的依赖关系

javascript - Rshinydashboard-根据用户输入显示/隐藏多个菜单项

linux - 使用 Javascript 运行远程命令

javascript - 单击时部分淡入,然后 - 淡出

javascript - 等待嵌套的子 promise

javascript - 我在使用 sequelize 在数据库中插入数据时遇到问题