gpt4 book ai didi

javascript - 如何获取重复对象键的长度

转载 作者:行者123 更新时间:2023-11-30 11:46:22 25 4
gpt4 key购买 nike

我想知道如何计算对象中重复键的数量。

我的对象是“a”,我用keys(a)得到了这个对象的key

keys(a) = ["name", "key", "com", "com"]

如何找到“com”在上面出现的总次数?我应该得到 2 的长度。

提前致谢

最佳答案

不可以,JavaScript 对象不能有重复的键。键必须都是唯一的。有个好thread on Stack Overflow关于这个话题。

如果假设您有对象数组,那是可能的。使用另一个对象作为计数器,像这样

var db = [
{Id: "1" , Player: "Nugent",Position: "Defenders"},
{Id: "2", Player: "Ryan",Position: "Forwards"},
{Id: "3" ,Player: "Sam",Position: "Forwards"},
{Id: "4", Player: "Bill",Position: "Midfielder"},
{Id: "5" ,Player: "Dave",Position: "Forwards"},
{Id: "6", Player: "Bill",Position: "Midfielder"}
]

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");
}
}

关于javascript - 如何获取重复对象键的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40879407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com