是否有
的等价物mysql_query("SELECT subcategory, COUNT(*) AS subcate FROM database GROUP BY subcategory");
在Js-Json中,我可以计算出有多少独特的子类别,并将它们打印在JSON数组中而不在mysql_query
过滤它们?
假设我使用
从数据库获取完整表mysql_query("SELECT * FROM database");
然后我将它放入json_encode($array);
然后我可以计算独特的子类别并从该JSON数组中打印出来吗?
JSON DATA
[{"category":"fish","subcategory":"angel","name":"angelfish juvenille"},{"category":"fish","subcategory":"angel","name":"angelfish adult"},{"category":"fish","subcategory":"clownfish","name":"clownfish juvenille"},{"category":"fish","subcategory":"clownfish","name":"clownfish adult"]
答案 0 :(得分:4)
您需要对数据列表进行简单的缩减。您为每个子类别保留一个带有键的对象,该值是具有该特定子类别的元素数量:
var data = [{"category":"fish","subcategory":"angel","name":"angelfish juvenille"},{"category":"fish","subcategory":"angel","name":"angelfish adult"},{"category":"fish","subcategory":"clownfish","name":"clownfish juvenille"},{"category":"fish","subcategory":"clownfish","name":"clownfish adult"}]
var result= data.reduce((all, element) => {
all[element.subcategory] = (all[element.subcategory] || 0) +1;
return all
}, {});
console.log(result);