2017-01-30 56 views
1

舉例來說,如果我有Typescript:有沒有一種方法可以獲得嵌套屬性的JavaScript對象中的所有鍵?

{ 
    "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"

+0

是。可能的重複http://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively – hackerrdave

+0

[循環通過對象(樹)遞歸]的可能重複(http://stackoverflow.com/questions/2549320 /循環通過對象樹遞歸) – nicovank

+0

有這個解決方案的一些問題http://stackoverflow.com/questions/41929287/typescript-what-c​​ould-be-causing-this-error-element-隱含地有任何t – icda

回答

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

+0

這段代碼似乎不能在打字稿中工作,因爲我遇到了很多「暗含有」錯誤 – icda

+0

這是因爲我提供的代碼是用基本JavaScript編寫的打字稿。 @icda –

相關問題