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

标签 javascript json node.js ejs

我有一个 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/

相关文章:

javascript - 更改悬停时添加到购物车文本

javascript - 当鼠标离开 div 时删除图像

c++ - 如何使用C++和Boost库生成JSON

jquery - Django 。 ajax调用后数量不会增加

javascript - 在 Node js 路由中发出 http 请求

javascript - 与固定导航栏重叠的英雄图片幻灯片

javascript - jQuery 可拖动在拖动开始时更改图像大小,在恢复时恢复原始大小

javascript - 访问深层 json 链接以进行重定向

node.js - Mocha 运行正确,但显示未定义

javascript - 如何在 RxJS 中将可变长度数据包流转换为固定长度数据包?