[英]how to get unique values from a list of objects?
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"
}
},
]
How to filter only unique values,如何仅过滤唯一值,
uniqueValues = ["medal","trophy"]
I tried,我试过了,
const uniqueTitles = new Set(games.category.title);
const uniqueTitles = [...new Set(games.category.title)]
//typescript error. const uniqueTitles = [...new Set(games.category.title)]
//打字错误。 useEffect(() => {
const uniqueTitles = games.filter((game:any) => {
return new Set(game.category.title);
})
setTitles(uniqueTitles);
},[])
You are using Set
as the return value for a filter function.您正在使用Set
作为过滤器函数的返回值。 Is it really intended that way?真的是这样打算的吗? Given the data:给定数据:
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"
}
},
]
You can do this:你可以这样做:
const uniqueValues = new Set();
data.forEach(record => uniqueValues.add(record.rank._type));
console.log(uniqueValues);
Assuming your array is called data
:假设您的数组称为data
:
const unique = [...new Set(data.map(item => item.rank._type))];
Credits: https://stackoverflow.com/a/58429784/6320971学分: https ://stackoverflow.com/a/58429784/6320971
Solution similar to your first try :类似于您的第一次尝试的解决方案:
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.map(elem => elem.rank._type)); uniqueValues.forEach(value => console.log(value));
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 result = data.filter((item, index) => { const itemIndex = data.findIndex(i => i.rank._type === item.rank._type) return itemIndex === index }) console.log(result)
简单的方法:
Array.from(new Set(dataList.map(i => i.name)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.