gpt4 book ai didi

javascript - 过滤数组以查找具有项目计数的唯一项目

转载 作者:行者123 更新时间:2023-12-02 14:25:26 25 4
gpt4 key购买 nike

你好,

我使用以下代码返回唯一的类别列表。

  stadium_cats: function () {
let stadiums =[
{"name":"Elland road","category":"football","country":"England"},
{"name":"Principality stadiums","category":"rugby","country":"Wales"},
{"name":"Twickenham","category":"rugby","country":"England"},
{"name":"Eden Park","category":"rugby","country":"New Zealand"}
];

var categories = stadiums.map(function(obj) {return obj.category});
categories = categories.filter(function(v,i) {return categories.indexOf(v) == i; });
return categories;
}

当我运行上面的代码时,我得到了一组唯一的stadium.category值。

有人可以帮我扩展它,这样我就可以得到一个对象数组,而不是返回一个数组:

[{"name":"football","count":"1"}{"name":"rugby","count":"3"}]

我想要这个名字以及它被推荐的次数?

这可能吗?

非常感谢,戴夫

最佳答案

您可以使用 forEach 循环和对象作为可选参数来完成此操作。

let stadiums = [{"name":"Elland road","category":"football","country":"England"},{"name":"Principality stadiums","category":"rugby","country":"Wales"},{"name":"Twickenham","category":"rugby","country":"England"},{"name":"Eden Park","category":"rugby","country":"New Zealand"}];

var result = [];
stadiums.forEach(function(e) {
if(!this[e.category]) {
this[e.category] = {name: e.category, count: 0}
result.push(this[e.category]);
}
this[e.category].count++;
}, {});

console.log(result);

关于javascript - 过滤数组以查找具有项目计数的唯一项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291979/

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