簡體   English   中英

在JavaScript中計算JSON文件中的鍵值對的實例

[英]Counting instances of key value pairs in JSON file in JavaScript

我正在處理具有許多屬性的大型對象數據集(請參見下文),並嘗試計算每個“類型”屬性的實例數量。 困難的部分是有很多不同類型,所以我不能從預定義的列表開始。

因此,以下數據的理想輸出為:

"Medic Response" : 2
"Aid Response" : 1

提前致謝。

賓語

address: "9001 Lake City Way Ne"
datetime : "2011-02-12T18:04:00.000"
incident_number : "F110013072"
latitude :"47.693931"
longitude : "-122.30552"
type : "Medic Response"

賓語

address : "97 S Main St"
datetime : "2011-02-16T18:46:00.000"
incident_number : "F110014403"
latitude : "47.600044"
longitude : "-122.334219"
type : "Aid Response"

賓語

address : "509 3rd Av"
datetime : "2011-02-12T07:30:00.000"
incident_number : "F110012897"
latitude : "47.602114"
longitude : "-122.330809"
report_location :
type : "Medic Response"

您可以使用名稱/計數類型的鍵/值哈希,然后遍歷對象集合,並隨即增加每個計數。 例如:

var counts = {};
var objects = [/*array of your objects*/];

objects.forEach(function (o) {
    // add the type to the hash if it is missing;
    // set initial count to 0
    if (!counts.hasOwnProperty(o.type)) {
        counts[o.type] = 0;
    }
    // increment the count based on the type
    counts[o.type] += 1;
});

console.log(counts);

您可以使用array.reduce將數據數組簡化為對象映射。

那是假設它是對象的平面陣列,並且您沒有嵌套的東西。

var count = data.reduce(function(prev, cur) {
  if (prev.hasOwnProperty(cur.type))
    prev[cur.type] += 1;
  else
    prev[cur.type] = 1;

  return prev;
}, {});

看到小提琴 減少文檔

您還可以使用reduce

objs.reduce(function(c, d){
  if (!c[d.type]) c[d.type] = 0;
  c[d.type]++;
  return c;
}, {});

為了確保我理解您的問題,請考慮以下效率低下的簡單實現:

var data = [{address:"9001 Lake...", ..., type:"Medic Response"}, 
            {address:"...", ..., type:"Aid Response",
            ...,
            {address""...", ..., type:"Medic Response"}];
var i, j, b, result = [] ;
for(i = 0; i < data.length; i ++)
{
    b = false ;
    for(j = 0; j < result.length; j++)
       if(result[j].key == data.type) {
           result[j].count += 1 ;
           b = true ;
           break ;
       }
     if (!b) {
        result.push({key:data.type, count: 1});
     }
}
// result is the frequency array of the "type" values in data array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM