首页 > 解决方案 > 多个过滤器/过滤器内过滤器 - React Native

问题描述

我怎么能在 React-Native 中做这样的事情:

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'},
           ]},

       ]

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

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

谢谢!:D

标签: react-nativefilter

解决方案


我不知道我是否正确理解了你的问题。这是我的解决方案。
如果您查询“Game5”,您将获得包含查询的整个对象

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);

您可以使用“过滤器”而不是“查找”,结果将是一个数组。
这是过滤器版本的示例。我添加了一个类别,以便您查看它是如何过滤的

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
这是官方的反应钩子解释


编辑:从你的评论中你可能想要这样的东西

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);


推荐阅读