gpt4 book ai didi

javascript - 如何从对象列表中获取唯一值?

转载 作者:行者123 更新时间:2023-12-05 03:22:28 27 4
gpt4 key购买 nike

数据:

[
{
"name": "Ankh of Anubis",
"rank": {
"_type": "medal",
"current": "ankh-of-anubis"
}
},
{
"name": "Bonus Roulette",
"rank": {
"_type": "medal",
"current": "bonus-roulette"
}
},
{
"name": "jetx",
"rank": {
"_type": "medal",
"current": "jetx"
}
},
{
"name": "Gates of Olympus",
"rank": {
"_type": "trophy",
"current": "gates-of-olympus"
}
},
]

如何只过滤唯一值,

uniqueValues = ["medal","trophy"]

我试过了,

  1. const uniqueTitles = new Set(games.category.title);
  2. const uniqueTitles = [...new Set(games.category.title)]//typescript 错误。
 useEffect(() => {
const uniqueTitles = games.filter((game:any) => {
return new Set(game.category.title);
})
setTitles(uniqueTitles);
},[])

最佳答案

您正在使用 Set 作为过滤器函数的返回值。真的是这么打算的吗?给定数据:

const data = [
{
"name": "Ankh of Anubis",
"rank": {
"_type": "medal",
"current": "ankh-of-anubis"
}
},
{
"name": "Bonus Roulette",
"rank": {
"_type": "medal",
"current": "bonus-roulette"
}
},
{
"name": "jetx",
"rank": {
"_type": "medal",
"current": "jetx"
}
},
{
"name": "Gates of Olympus",
"rank": {
"_type": "trophy",
"current": "gates-of-olympus"
}
},
]

你可以这样做:

const uniqueValues = new Set();
data.forEach(record => uniqueValues.add(record.rank._type));
console.log(uniqueValues);

这是 link .

关于javascript - 如何从对象列表中获取唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72717983/

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