我在过滤指定的carmake时使用以下代码并计算其数量。
以下是数据和代码:
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);
我需要做的是创建一个循环,基本上检查所有标签并计算每个标签的数量。
我知道如何手动指定每个,但我该如何自动执行此操作,以便它只扫描标记并计算它们?
我想要的最终结果是最终得到一个包含所有总数的数组。
答案 0 :(得分: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)
答案 1 :(得分:0)
这很简单,你需要迭代数组并计算属性键
var response = [];
obj.garages.forEach(function(item) {
response.push(Object.keys(item.tags).length);
});
答案 2 :(得分:-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);