【问题标题】:How can I access an array of multi-level objects?如何访问多级对象数组?
【发布时间】:2017-09-07 06:26:56
【问题描述】:

通过查看“Array”图像,我如何访问该数组的所有级别?

我尝试做一个 foreach 但这只允许我访问第一个对象,我无法访问填充字符串的第二个对象。

    for (var key in result)
  {
     if (result.hasOwnProperty(key))
        {
          console.log(key, result[key]);

              for(var item in result[key])
                {
                  console.log(item);
                 }
          }
}

我也试过了:

result[key[item]]

但它似乎是未定义的。

我知道通过名称访问所有元素很容易,但名称会不断变化,因此解决方案应该是动态的。

我在 cmets 上添加了 Demo 以查看行为。

【问题讨论】:

标签: javascript arrays arraylist javascript-objects


【解决方案1】:

Object.keys(obj) 返回obj 中的键数组。

var obj = {
  a: 1,
  b: 2,
  m: 3,
  x: 4,
  y: 5,
  z: 6
}

//get all the keys in an array:
var keys = Object.keys(obj)
console.log("keys: " + keys);

//iterate through the object by its keys:
for (var i = 0; i < keys.length; i++){
  console.log("key " + keys[i] + " has value " + obj[keys[i]]);
}

根据您的评论更新

我认为您要求将此解决方案应用于任意深度的对象。我的解决方案是将前面的技巧包装在一个函数中,如果有嵌套对象,则递归调用它:

var obj = {
  a: {foo:"bar",foof:"barf"},
  b: 2,
  m: 3,
  x: {baz:{really:{more:{objects: "yeah, there could be a lot"}}}},
  y: 5,
  z: 6
}

function getKeysDeep(obj,prefix){
  //get all the keys in an array:
  var keys = Object.keys(obj)
  //console.log(prefix + "keys: " + keys);

  //iterate through the object by its keys:
  for (var i = 0; i < keys.length; i++){
    if (obj[keys[i]] !== null && typeof obj[keys[i]] === 'object') {
      console.log("key " + keys[i] + "'s value is an object");
      getKeysDeep(obj[keys[i]],prefix + keys[i] + ": ");
    } else {
      console.log(prefix + "key " + keys[i] + " has value " + obj[keys[i]]);
    }
  }
}

getKeysDeep(obj,"")

【讨论】:

  • 这允许我访问第一个对象连接,但如果我有一个:{ 1: test} 它不允许我访问“测试”
【解决方案2】:

这个循环也有效!

Object.keys(result).forEach(function (key) {
      console.log(result[key]);
      var test = result[key];
      Object.keys(test).forEach(function (key) {
         console.log(test[key]);
         var testTwo = test[key];
          Object.keys(testTwo).forEach(function (key) {
            console.log(testTwo[key]);
            var testThree = testTwo[key];
          });
       });
    });

但@nvioli 的答案更准确。

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 2010-12-11
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多