![](/img/trans.png)
[英]How to get objects with unique values for specific keys from array of objects?
[英]how to get unique values from a list of objects?
數據:
[
{
"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"]
我試過了,
const uniqueTitles = new Set(games.category.title);
const uniqueTitles = [...new Set(games.category.title)]
//打字錯誤。 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);
這是鏈接。
假設您的數組稱為data
:
const unique = [...new Set(data.map(item => item.rank._type))];
學分: https ://stackoverflow.com/a/58429784/6320971
類似於您的第一次嘗試的解決方案:
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.