gpt4 book ai didi

javascript - 从 JavaScript 中的 JSON 对象访问多级 key

转载 作者:行者123 更新时间:2023-12-03 05:12:03 24 4
gpt4 key购买 nike

我有一个 javascript 函数,它返回这样的响应(我正在使用 nodejs 和 ejs):

"index_1": {
"mappings": {
"type_1": {
"properties": {
"field_1": {
"type": "string"
},
"field_2": {
"type": "string"
}
}
},
"type_2": {
"properties": {
"field_1": {
"type": "string"
},
"field_2": {
"type": "string"
},
"field_3": {
"type": "string"
}
}
}
}
}

现在,我需要从响应中访问第二级或第三级 key 。假设我想要一个这样的列表:

type_1
type_2

field_1
field_2
field_3

我怎样才能做到这一点?如果我使用callback(Object.keys(response)),那么它会返回index_1。谁能指出我正确的方向?

最佳答案

要获取子对象的键,您需要将此特定子对象传递给Object.keys():

var data = {"index_1":{"mappings":{"type_1":{"properties":{"field_1":{"type":"string"},"field_2":{"type":"string"}}},"type_2":{"properties":{"field_1":{"type":"string"},"field_2":{"type":"string"},"field_3":{"type":"string"}}}}}};

console.log(Object.keys(data.index_1.mappings));
// ["type_1", "type_2"]

console.log(Object.keys(data.index_1.mappings.type_2.properties));
// ["field_1", "field_2", "field_3"]

关于javascript - 从 JavaScript 中的 JSON 对象访问多级 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com