[英]How to count number of objects in an array per key?
I have a JavaScript array which has the following contents:我有一个 JavaScript 数组,其中包含以下内容:
var products = [
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
{category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];
I want to count the number of unique entries in each key.我想计算每个键中唯一条目的数量。
For example,例如,
For the key category
there are 2 unique entries.对于关键category
,有 2 个唯一条目。
For the key name
there are 5 unique entries.对于键name
,有 5 个唯一条目。
I tried using Object.keys(products).length
, but that only gives the total number of rows in the array.我尝试使用Object.keys(products).length
,但这仅给出了数组中的总行数。
How can I get the counts?我怎样才能得到计数?
You can reduce array to get unique values as keys of reduced object and then apply Object.keys()
, for example:您可以减少数组以获取唯一值作为减少对象的键,然后应用Object.keys()
,例如:
var categoryCount = Object.keys(products.reduce(function(r, o) {
r[o.category] = 1;
return r;
}, {})).length;
In ECMAScript 2015 you can use Set data structure to get unique values:在 ECMAScript 2015 中,您可以使用 Set 数据结构来获取唯一值:
const categoryCount = new Set(products.map(p => p.category)).size;
You can achieve this by following您可以通过以下方式实现此目的
var map = {};
products.map(function(product){
map[product.category] = undefined;
});
console.log(Object.keys(map).length);
I was able to achieve the same through a one line code.我能够通过一行代码实现相同的目标。 I am unsure if this is the most efficient one though:我不确定这是否是最有效的方法:
var categoryCount = $.unique(products.map(function (d) {return (d.category);}));
alert(categoryCount.length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.