使用嵌套的$ .each循环遍历对象

时间:2016-08-30 03:07:30

标签: javascript jquery loops object nested-loops

我在使用嵌套的$ .each循环访问对象时遇到问题。该对象是一系列嵌套在rootObject下的相同类型/类的对象。

对象

var rootObject ={};

rootObject.reportObject1.name = "reportObject1 Name";
rootObject.reportObject1.prop1 = "reportObject1 Prop1_Value";
rootObject.reportObject1.prop2 = "reportObject1 Prop2_Value";

rootObject.reportObject1.reportObjectA.name = "reportObjectA Name";
rootObject.reportObject1.reportObjectA.prop1 = "reportObjectA Prop1_Value";
rootObject.reportObject1.reportObjectA.prop2 = "reportObjectA Prop2_Value";

循环

$.each(rootObject, function(index0, value0){
  console.log(value0.name);

  $.each(value0, function(index1, value1){
    console.log(value1.name);
  }

}

问题

  1. value1.name返回循环中名称以外的对象属性。它似乎试图返回prop1&的value.name。 prop2,导致“未定义”值。

  2. 在调试期间查看value0的值时,value0在进入嵌套循环时似乎会丢失其值。来自父循环的console.log(value1.name)value0变为undefined;

  3. 在调试过程中查看子循环(index1, value1)时,我发现value1现在等于value0.name,而index1等于“name”。

1 个答案:

答案 0 :(得分:2)

您可以自动定义一个级别的属性,但是对于两个属性,您需要停止并实例化父级:

var rootObject ={};

rootObject.reportObject1 = {}; // HERE
rootObject.reportObject1.name = "reportObject1 Name";
rootObject.reportObject1.prop1 = "reportObject1 Prop1_Value";
rootObject.reportObject1.prop2 = "reportObject1 Prop2_Value";

rootObject.reportObject1.reportObjectA = {}; // and HERE
rootObject.reportObject1.reportObjectA.name = "reportObjectA Name";
rootObject.reportObject1.reportObjectA.prop1 = "reportObjectA Prop1_Value";
rootObject.reportObject1.reportObjectA.prop2 = "reportObjectA Prop2_Value";

如果没有这些,这些属性实际上都没有定义,导致您的undefined结果。

下一个问题是另一个语法问题:您在两个$.each()来电时错过了右括号:

$.each(rootObject, function(index0, value0){
  console.log(value0.name);

  $.each(value0, function(index1, value1){
    console.log(value1.name);
  }); // HERE

}); // and HERE

通过这两个修复程序,您的控制台输出显示:

reportObject1 Name
undefined (x3)
reportObjectA Name

要获得正确的输出或至少一些样本输出,您可以使用这个小宝石(from here)。因为你的结构可能有两个以上的级别,所以递归似乎是合适的。

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //iterate across o, passing keys as k and values as v
    $.each(o, function(k,v){

        //if v has nested depth
        if(typeof v == "object"){

            //write the key to the console
            console.log(s+k+": ");

            //recursively call enumerate on the nested properties
            enumerate(v,s+"  ");

        } else {

            //log the key & value
            console.log(s+k+": "+String(v));
        }
    });
}

如果您尝试enumerate(rootObject),您将获得:

reportObject1: 
   name: reportObject1 Name
   prop1: reportObject1 Prop1_Value
   prop2: reportObject1 Prop2_Value
   reportObjectA: 
     name: reportObjectA Name
     prop1: reportObjectA Prop1_Value
     prop2: reportObjectA Prop2_Value