从JSON数组中获取密钥而不重复

时间:2017-07-06 02:23:12

标签: javascript arrays json elasticsearch

考虑从发送到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”可以硬编码到columns对象中,因为它始终存在。

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

1 个答案:

答案 0 :(得分:0)

如果它只是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) });