首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个过滤器/过滤器内的过滤器-反应本机

多个过滤器/过滤器内的过滤器-反应本机
EN

Stack Overflow用户
提问于 2020-07-16 14:33:19
回答 1查看 134关注 0票数 2

我怎样才能做出这样的反应--本地人:

代码语言:javascript
复制
data = [
           {id:1,title:'Action',games:[
               {id:1,title:'Game1'},
               {id:2,title:'Game2'},
               {id:3,title:'Game3'},
           ]},
           {id:2,title:'Horror',games:[
               {id:1,title:'Game1'},
               {id:2,title:'Game2'},
               {id:3,title:'Game3'},
           ]},

       ]

每次更新查询字符串时,都要在类别中查找游戏。

只返回包含有搜索字符的游戏的类别。

谢谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-16 14:47:37

我不知道我是否正确理解了你的问题。这是我的解决方案。

如果您查询"Game5“,您将得到包含查询的整个对象

代码语言:javascript
复制
const data = [
  {
    id: 1,
    title: "Action",
    games: [
      { id: 1, title: "Game1" },
      { id: 2, title: "Game2" },
      { id: 3, title: "Game3" },
    ],
  },
  {
    id: 2,
    title: "Horror",
    games: [
      { id: 1, title: "Game4" },
      { id: 2, title: "Game5" },
      { id: 3, title: "Game6" },
    ],
  },
];

const query = "Game5";
const result = data.find((category) =>
  category.games.find((g) => g.title === query)
);

console.log(result);

您可以使用“筛选”代替“查找”,结果将是一个数组。

这是过滤器版本的示例。我再添加一个类别,这样您就可以看到它是如何过滤的。

代码语言:javascript
复制
const data = [
  {
    id: 1,
    title: "Action",
    games: [
      { id: 1, title: "Game1" },
      { id: 2, title: "Game2" },
      { id: 3, title: "Game3" },
    ],
  },
  {
    id: 2,
    title: "Horror",
    games: [
      { id: 1, title: "Game1" },
      { id: 2, title: "Game2" },
      { id: 3, title: "Game3" },
    ],
  },
  {
    id: 3,
    title: "Comedy",
    games: [
      { id: 1, title: "Game5" },
      { id: 2, title: "Game6" },
      { id: 3, title: "Game7" },
    ],
  },
];

const query = "Game2";
const result = data.filter((category) =>
  category.games.find((g) => g.title === query)
);

console.log(result);

如果您编写类组件,您可能希望查看生命周期componentDidUpdate,但是如果您编写函数组件,则可能需要使用useEffect

这是官方反应钩解释

编辑:在您的评论中,您可能需要这样的内容

代码语言:javascript
复制
const data = [
  {
    id: 1,
    title: "Action",
    games: [
      { id: 1, title: "Game1" },
      { id: 2, title: "Game2" },
      { id: 3, title: "Game3" },
    ],
  },
  {
    id: 2,
    title: "Horror",
    games: [
      { id: 1, title: "Game1" },
      { id: 2, title: "Game2" },
      { id: 3, title: "Game3" },
    ],
  },
  {
    id: 3,
    title: "Comedy",
    games: [
      { id: 1, title: "Game5" },
      { id: 2, title: "Game6" },
      { id: 3, title: "Game7" },
    ],
  },
];

const query = "Game5";
let result = null;
data.forEach((category) => {
  const game = category.games.filter((g) => g.title === query);
  if (game.length) result = { ...category, games: game };
});

console.log(result);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62937070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档