查找对象中重复属性值的计数

编程入门 行业动态 更新时间:2024-10-18 16:55:20
本文介绍了查找对象中重复属性值的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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"); } }

更多推荐

查找对象中重复属性值的计数

本文发布于:2023-11-07 06:02:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:象中   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!