例如,如果我有
{
"key1":{
"key2":[
{
"key3":[
{
"key4":{
"key5":0
}
},
{
"key6":{
"key7":""
}
}
]
},
{
"key8":{
"key9":true
}
}
]
}
}
有没有办法像这样获取所有 key ?
["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"
最佳答案
您需要一个递归函数才能进行迭代。
尝试这样
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 - typescript : Is there a way to get all the keys in a Javascript object with nested properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41928610/