【问题标题】:how to get unique values from a list of objects?如何从对象列表中获取唯一值?
【发布时间】:2022-06-22 23:21:14
【问题描述】:

数据:

[
  {
    "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);
  },[])

【问题讨论】:

    标签: javascript reactjs arrays


    【解决方案1】:

    您正在使用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

    【讨论】:

      【解决方案2】:

      与您的第一次尝试类似的解决方案:

      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));
      console.log(uniqueValues);

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 1970-01-01
        • 1970-01-01
        • 2015-02-11
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        • 2011-11-27
        • 2019-01-03
        相关资源
        最近更新 更多