java脚本将嵌套对象带到根级别

时间:2017-02-14 21:07:44

标签: javascript lodash

我有一个看起来像这样的json对象:

{
  "total": 298,
  "max_score": 5.2472496,
  "hits": [
    {
      "_index": "kafkajmx2",
      "_type": "logs",
      "_id": "AVo-VsUdponm9zQGYYS5",
      "_score": 5.2472496,
      "_source": {
        "metric_value_number": 134,
        "path": "/home/usrxxx/logstash-5.2.0/bin/jmxconf",
        "@timestamp": "2017-02-14T20:35:58.266Z",
        "metric_name": "IsrExpandsPerSec.Count",
        "@version": "1",
        "host": "localhost",
        "metric_type": "ReplicaManager",
        "metric_path": "node1.kafka.server:type=ReplicaManager,name=IsrExpandsPerSec.Count",
        "type": null,
        "metric_node": "node1.kafka.server"
      }
    },
    {
      "_index": "kafkajmx2",
      "_type": "logs",
      "_id": "AVo-V69Yponm9zQGYYwS",
      "_score": 5.2472496,
      "_source": {
        "metric_value_number": 134,
        "path": "/home/usrxxx/logstash-5.2.0/bin/jmxconf",
        "@timestamp": "2017-02-14T20:36:58.216Z",
        "metric_name": "IsrExpandsPerSec.Count",
        "@version": "1",
        "host": "localhost",
        "metric_type": "ReplicaManager",
        "metric_path": "node1.kafka.server:type=ReplicaManager,name=IsrExpandsPerSec.Count",
        "type": null,
        "metric_node": "node1.kafka.server"
      }
    }
]
}

我想要做的是将_source对象调到根级别,如下所示:

{
            "metric_value_number": 134,
            "path": "/home/usrxxx/logstash-5.2.0/bin/jmxconf",
            "@timestamp": "2017-02-14T20:36:58.216Z",
            "metric_name": "IsrExpandsPerSec.Count",
            "@version": "1",
            "host": "localhost",
            "metric_type": "ReplicaManager",
            "metric_path": "node1.kafka.server:type=ReplicaManager,name=IsrExpandsPerSec.Count",
            "type": null,
            "metric_node": "aesdp0101.kafka.server"
          },
{
            "metric_value_number": 134,
            "path": "/home/usrxxx/logstash-5.2.0/bin/jmxconf",
            "@timestamp": "2017-02-14T20:35:58.266Z",
            "metric_name": "IsrExpandsPerSec.Count",
            "@version": "1",
            "host": "localhost",
            "metric_type": "ReplicaManager",
            "metric_path": "node1.kafka.server:type=ReplicaManager,name=IsrExpandsPerSec.Count",
            "type": null,
            "metric_node": "aesdp0101.kafka.server"
          }

我不确定如何在本机javascript中执行此操作,或者如果在lodash中还有一种方法可以执行此操作...

我试过这样做,但我认为_中的_source影响了代码?

      var metricData = [];
      for (var i=0; i < response.length; i++) {

         metricData.push(response[i]._source);
         console.log("metric data: ", metricData);

      };

1 个答案:

答案 0 :(得分:2)

您是否忘记选择&#34;点击&#34;?

尝试以下方法:

metricData = response.hits.map(hit => hit["_source"])