react-native - 多个过滤器/过滤器内过滤器 - 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
解决方案
我不知道我是否正确理解了你的问题。这是我的解决方案。
如果您查询“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);
推荐阅读
- cockroachdb - Cockroachdb 在启动后使用了所有内存,即使数据大小只有 2GiB
- javascript - 输入标签未在 React 中呈现
- swift - SFSpeechRecognizer 失败并出现错误 kAFAssistantErrorDomain Code=1107
- java - 是否可以使用注释来禁止类中的依赖关系?
- swift - 为什么lazy.compactMap.first 映射'first'元素两次?
- laravel - 如何在laravel中加入2个表的多个结果并返回它们
- javascript - Knockout JS,如何在更改可观察数组中的值时更改样式属性
- c++ - 可以具有不同基成员实现的类的最佳实现
- c++ - 使用类型双关的 POD 结构序列化
- asp.net - 无法设置 Azure 存储容器权限