简体   繁体   English

如何访问多级对象数组?

[英]How can I access an array of multi-level objects?

By looking at the " Array " image, how can I access all levels of this array? 通过查看“ 数组 ”图像,如何访问该数组的所有级别?

I tried doing a foreach but this only allows me to access to the first object, I can't acces the second object filled with strings. 我尝试进行一次foreach,但这仅允许我访问第一个对象,而我无法访问第二个用字符串填充的对象。

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

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

I also tried: 我也尝试过:

result[key[item]]

But it appears to be undifined. 但这似乎是不确定的。

I know it's easy to access all elements by the name, but the names change constantly, so the solution should be dynamic. 我知道按名称访问所有元素很容易,但是名称不断变化,因此解决方案应该是动态的。

I added the Demo on the comments to see behavior. 我在评论上添加了演示,以查看行为。

Object.keys(obj) returns an array of the keys in obj . 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]]); } 

Update based on your comment 根据您的评论更新

I think you're asking to apply this solution to an arbitrary-depth object. 我认为您是在要求将此解决方案应用于任意深度的对象。 My solution would be to wrap the previous trick in a function and call it recursively if there are nested objects: 我的解决方案是将先前的技巧包装到函数中,如果存在嵌套对象,则以递归方式调用它:

 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,"") 

This loop worked too! 这个循环也起作用!

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

But @nvioli answer is more accurate. 但是@nvioli的答案更准确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM