【问题标题】:Grab Keys from JSON Array Without Repeating从 JSON 数组中获取键而不重复
【发布时间】:2017-12-09 20:45:44
【问题描述】:

考虑以下从发送到 Elasticsearch 集群的请求返回的 JSON 数组:

[
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "vodafone UK",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo",
            "demo-country-code": "GB"
        }
    },
    {
        "_type": "Event example",
        "_source": {
            "democarrier_s": "Verizon",
            "m-Ecosystem_s": "iOS",
            "demo-application": "demo1",
            "demo-country-code": "US"
        }
    }
]

我正在尝试找出如何在不重复和不硬编码任何值的情况下从该文档中获取所有唯一键,并将它们存储到以下形式的对象中:

columns = ['_type', '_source.democarrier_s', '_source.m-Ecosystem_s', '_source.demo-application', '_source.demo-country-code'];

有人可以帮我弄清楚如何实现这一目标吗?我一直在尝试遍历文档并存储密钥,但我无法弄清楚。 '_type' 可以硬编码到列对象中,因为它会一直存在。

提前感谢您的帮助和时间。

【问题讨论】:

    标签: javascript arrays json elasticsearch


    【解决方案1】:

    如果只有 2 个级别,您可以这样做:

    var data = [
        {
            "_type": "Event example",
            "_source": {
                "democarrier_s": "vodafone UK",
                "m-Ecosystem_s": "iOS",
                "demo-application": "demo",
                "demo-country-code": "GB"
            }
        },
        {
            "_type": "Event example",
            "_source": {
                "democarrier_s": "Verizon",
                "m-Ecosystem_s": "iOS",
                "demo-application": "demo1",
                "demo-country-code": "US"
            }
        }
    ]
    
    var keys = [];
    data.forEach(function(item) {
    
      for (var key in item) {
        var hasProperties = false;
        
        if (typeof item[key] !== 'string') {
          
          for (var key2 in item[key]) {
            hasProperties = true;
            
            var keyName = key + "." + key2;
    
            if (keys.indexOf(keyName) < 0)
                keys.push(keyName);
          }
        }
        
        if (!hasProperties && keys.indexOf(key) < 0) {
           keys.push(key);
        }
     }
    });
    
    keys.forEach(function (k) { console.log(k) });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-01
      • 2016-10-28
      • 1970-01-01
      • 2019-03-04
      • 2023-04-05
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      相关资源
      最近更新 更多