【问题标题】:Typescript: Is there a way to get all the keys in a Javascript object with nested properties?Typescript:有没有办法获取具有嵌套属性的 Javascript 对象中的所有键?
【发布时间】:2017-06-15 04:18:39
【问题描述】:

例如,如果我有

{
   "key1":{
      "key2":[
         {
            "key3":[
               {
                  "key4":{
                     "key5":0
                  }
               },
               {
                  "key6":{
                     "key7":""
                  }
               }
            ]
         },
         {
            "key8":{
               "key9":true
            }
         }
      ]
   }
}

有没有办法像这样得到所有的钥匙?

["key1", "key2", "key3", "key4", "key5", "key6", "key7", "key8", "key9"]

编辑:我在这里尝试了suggestion,但没有成功Typescript: what could be causing this error? "Element implicitly has an 'any' type because type 'Object' has no index signature"

【问题讨论】:

标签: javascript recursion javascript-objects


【解决方案1】:

您需要一个递归函数才能进行迭代。

这样试试

var obj = {
  "key1": {
    "key2": [{
      "key3": [{
        "key4": {
          "key5": 0
        }
      }, {
        "key6": {
          "key7": ""
        }
      }]
    }, {
      "key8": {
        "key9": true
      }
    }]
  }
};
var keys = [];

function collectKey(obj) {
  if (obj instanceof Array) {
    //console.log("array");
    for (var i = 0; i < obj.length; i++) {
      collectObj(obj[i]);
    }
  } else if (typeof obj == "object") {
    //console.log("object");
    collectObj(obj)
  } else {
    return;
  }
}

function collectObj(obj) {
  for (var i = 0; i < Object.keys(obj).length; i++) {
    keys.push(Object.keys(obj)[i]);
    collectKey(obj[Object.keys(obj)[i]]);
  }
}
collectKey(obj);
console.log(keys);

【讨论】:

  • 这段代码在打字稿中似乎不起作用,因为我遇到了许多“隐含的”错误
  • 那是因为我提供的代码是用基本的javascript而不是打字稿编写的。 @icda
猜你喜欢
  • 2010-11-23
  • 2019-03-29
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
相关资源
最近更新 更多