2017-02-14 30 views
0

我有一個JSON對象,看起來像這樣:Java腳本帶來嵌套對象達根級別

{ 
    "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); 

     }; 
+2

你沒有一個數組'你的問題中的任何地方metricData'。 – Lee

+0

對不起,忘了包括,我有代碼中的'var metricData = []'...做了編輯... – user2061886

+0

看到下面的答案,看起來正確。 – Lee

回答

2

你忘了選擇「點擊」?

嘗試以下操作:

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

當我嘗試時出現此錯誤...'TypeError:response.hits.map不是函數' – user2061886

+0

什麼是響應對象?你沒有提到這一點。我懷疑你應該從中選擇json數據。或者你給了我們錯誤的響應格式,「命中」不是數組。 –

+0

對不起...我的部分錯字....再次...一直在這裏一天....但它的工作,非常感謝! – user2061886