2016-10-18 84 views
0

當我使用以下代碼來過濾指定的carmake並計算有多少。Javascript循環來計算每個指定的字段並計數每個指定的字段總數

下面是數據和代碼:

var obj = obj = { 
    "garages": [{ 
     "id": "1", 
     "carId": "1", 
     "tags": { 
      "483": "carmake1", 
      "485": "carmake3" 
     } 
    }, 
    { 
     "id": "2", 
     "carId": "1", 
     "tags": { 
      "483": "carmake1", 
      "485": "carmake3" 
     } 
    }, 
    { 
     "id": "3", 
     "carId": "2", 
     "tags": { 
      "484": "carmake2", 
      "485": "carmake3" 
     } 
    }, 
    { 
     "id": "4", 
     "carId": "2", 
     "tags": { 
      "483": "carmake1", 
      "485": "carmake3" 
     } 
    }, 
    { 
     "id": "5", 
     "carId": "3", 
     "tags": { 
      "484": "carmake2", 
      "485": "carmake3" 
     } 
    }, 
] 
}; 

    count = obj.garages.filter(function(item) { 
     return item.tags[483] === "carmake1" 
    }).length; 

    console.log(count); 

我需要做的是建立一個循環,基本上會檢查所有的標籤和算多少也有各自的什麼。

我知道如何手動指定每個,但我怎麼能自動做到這一點,以便它只會掃描標籤並對它們進行計數?

我希望得到的最終結果是包含所有總數的數組。

+1

'OBJ = OBJ = {'? – evolutionxbox

+2

可能重複的[Javascript數有多少車庫有carmake1](http://stackoverflow.com/questions/40107350/javascript-count-how-many-garages-have-carmake1) –

+0

@EmilS.Jørgensen哇。這幾乎就像OP爲他需要完成的每項任務提出一個單獨的問題。 – evolutionxbox

回答

0

你可以指望的手動而不是過濾器:

var obj={garages:[{id:"1",carId:"1",tags:{483:"carmake1",485:"carmake3"}},{id:"2",carId:"1",tags:{483:"carmake1",485:"carmake3"}},{id:"3",carId:"2",tags:{484:"carmake2",485:"carmake3"}},{id:"4",carId:"2",tags:{483:"carmake1",485:"carmake3"}},{id:"5",carId:"3",tags:{484:"carmake2",485:"carmake3"}}]}; 
 

 
var r = {}; 
 

 
obj.garages.forEach(function(o) { 
 
    for (var t in o.tags) { 
 
    r[t] = (r[t] || 0) + 1 
 
    } 
 
}) 
 

 
console.log(r)

0

這很簡單,你需要遍歷數組和計數propertie鍵

var response = []; 
obj.garages.forEach(function(item) { 
    response.push(Object.keys(item.tags).length); 
}); 

檢查這個小提琴out https://jsfiddle.net/bvccedoo/

-1

除非我記錯了,你也可以使用Array.prototype.map

var obj={garages:[{id:"1",carId:"1",tags:{483:"carmake1",485:"carmake3"}},{id:"2",carId:"1",tags:{483:"carmake1",485:"carmake3"}},{id:"3",carId:"2",tags:{484:"carmake2",485:"carmake3"}},{id:"4",carId:"2",tags:{483:"carmake1",485:"carmake3"}},{id:"5",carId:"3",tags:{484:"carmake2",485:"carmake3"}}]}; 
 

 
var result = obj.garages.map(function(item) { 
 
    return Object.keys(item.tags).length; 
 
}); 
 
console.log(result);

+0

爲什麼downvote?請你解釋一下嗎? – evolutionxbox