查找对象中重复属性值的计数 [英] Find the count of duplicate property values in an object
本文介绍了查找对象中重复属性值的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var db = [
{Id: "201" , Player: "Nugent",Position: "Defenders"},
{Id: "202", Player: "Ryan",Position: "Forwards"},
{Id: "203" ,Player: "Sam",Position: "Forwards"},
{Id: "204", Player: "Bill",Position: "Midfielder"},
{Id: "205" ,Player: "Dave",Position: "Forwards"},
];
如何按Position
查找重复对象的数量.
How can I can I find the number of duplicate objects by Position
.
请注意,我有重复的值作为"Forwards"
(第二个,第三个和最后一个对象)
Notice I have duplicated value as "Forwards"
(second, third and last object)
我尝试做:
for (var key in db) {
var value = db[key];
if ( count of duplicated values == 3) {
console.log("we have three duplicated values)
}
}
在循环对象时是否可以这样做?
Is it possible to do this while the objects are being looped?
推荐答案
使用另一个对象作为计数器,
Use another object as a counter, like this
var counter = {};
for (var i = 0; i < db.length; i += 1) {
counter[db[i].Position] = (counter[db[i].Position] || 0) + 1;
}
for (var key in counter) {
if (counter[key] > 1) {
console.log("we have ", key, " duplicated ", counter[key], " times");
}
}
这篇关于查找对象中重复属性值的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文