如何循环JS中的多级对象?

时间:2015-04-09 01:58:13

标签: javascript loops object properties

我如何遍历下面对象中的每个value:属性?我在console.log下面的尝试显然不起作用,但这正是我想要完成的。 console.log(key)将输出"A1" "A2",但我无法弄清楚如何循环并检索更深层次属性的名称或值。

var object = {
    A1: {
        B1: {
            C1: "A"
        },
        B2: {
            C1: "B"
        },
        B3: {
            C1: "C"
        },
    },
    A2: {
        B4: {
            C1: "D"
        },
        B5: {
            C1: "E"
        },
        B6: {
            C1: "F"
        }
    }
};

for (var key in object) {
    console.log(object[key][key].value);
}

3 个答案:

答案 0 :(得分:3)

你可能正在寻找嵌套for循环。为了迭代这个特定的对象(我们知道它只有三个嵌套级别)你可以尝试这样的事情:

for(var key1 in object) {
  for(var key2 in object[key1]) {
    for(var key3 in object[key1][key2]) {
      console.log(object[key1][key2][key3]);
    }
  }
}

输出:

"A"
"B"
"C"
"D"
"E"
"F"

答案 1 :(得分:2)

var object = {
    A1: {
        B1: {
            C1: "A"
        },
        B2: {
            C1: "B"
        },
        B3: {
            C1: "C"
        },
    },
    A2: {
        B4: {
            C1: "D"
        },
        B5: {
            C1: "E"
        },
        B6: {
            C1: "F"
        }
    }
};

function printObj(obj) {
  for (var key in obj) {
    var value = obj[key];
    if (typeof value === 'object') {
      printObj(value);
    } else {
      console.log(value);
    }
  }
}

printObj(object);

只需使用递归

答案 2 :(得分:1)

使用嵌套循环:

var object = {
  A1: {
    B1: {
      C1: "A"
    },
    B2: {
      C1: "B"
    },
    B3: {
      C1: "C"
    },
  },
  A2: {
    B4: {
      C1: "D"
    },
    B5: {
      C1: "E"
    },
    B6: {
      C1: "F"
    }
  }
};
for (var key1 in object) {
  var e1 = object[key1];
  for (var key2 in e1) {
    var e2 = e1[key2];
    for (var key3 in e2) {
      console.log(e2[key3]);
    }
  }
}