我知道有很多关于如何从 json 获取 key 的线程,但我没有找到我的具体案例。我的问题有点棘手。 例如,考虑这个 json:
{
"User": {
"Username": "testuser",
"Roles": ["Chief", "Other"],
"Languages": ["it", "en"],
"IsActive": true,
"Family": {
"Mother": "Mary",
"Father": "Mike"
}
},
"Timestamp": null
}
我需要获取所有嵌套键的列表,例如:
User.Usernames
User.Roles
User.Languages
User.IsActive
User.Family.Mother
User.Family.Father
Timestamp
而不是
User
Usernames
Roles
Languages
IsActive
Family
Mother
Father
Timestamp
我不想知道每个键的值。我无法使用值搜索键,因为它每次都会改变。 代码:
Object.keys(myJson)
只给我 json 的根元素(在本例中为“User”和“Timestamp”)。 我正在使用 typescript 2.9.2 和 Angular 6。
谢谢。
最佳答案
试试这个:
let obj ={
"User": {
"Username": "testuser",
"Roles": ["Chief", "Other"],
"Languages": ["it", "en"],
"IsActive": true,
"Family": {
"Mother": "Mary",
"Father": "Mike"
}
},
"Timestamp": null
}
var list = [];
getProps(obj);
function getProps(obj, parent=null) {
for (var props in obj) {
if (typeof (obj[props]) == "object" && obj[props] !== null && !Array.isArray(obj[props]) ) {
getProps(obj[props],props)
}
else if (parent !== null) {
list.push(parent+"."+props);
}
else {
list.push(props);
}
}
}
console.log(list);
关于json - 如何从 typescript 中的 json 获取串联键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53155560/