簡體   English   中英

如何從對象列表中獲取唯一值?

[英]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"]

我試過了,

  1. const uniqueTitles = new Set(games.category.title);
  2. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM