繁体   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