如何过滤含嵌套对象的卡牌数组?解决ban_ocg读取报错问题
解决卡牌数组中嵌套对象的过滤问题
你需要从包含10000张卡牌的数组中筛选出banlist_info.ban_ocg等于"Forbidden"的卡牌,但部分卡牌没有banlist_info属性,导致直接访问嵌套属性时报错。
数据库示例
[ { id: 15341821, name: 'Dandylion', type: 'Effect Monster', desc: 'If this card is sent to the Graveyard: Special Summon 2 "Fluff Tokens" (Plant-Type/WIND/Level 1/ATK 0/DEF 0) in Defense Position. These Tokens cannot be Tributed for a Tribute Summon during the turn they are Special Summoned.', atk: 300, def: 300, level: 3, race: 'Plant', attribute: 'EARTH', banlist_info: { ban_tcg: 'Forbidden', ban_ocg: 'Forbidden', ban_md: 'Forbidden' }, }, { id: 43694650, name: 'Danger!? Jackalope?', type: 'Effect Monster', desc: 'You can reveal this card in your hand; your opponent randomly chooses 1 card from your entire hand, then you discard the chosen card. Then, if the discarded card was not "Danger!? Jackalope?", Special Summon 1 "Danger!? Jackalope?" from your hand, and if you do, draw 1 card. If this card is discarded: You can Special Summon 1 "Danger!" monster from your Deck in Defense Position, except "Danger!? Jackalope?". You can only use this effect of "Danger!? Jackalope?" once per turn.', atk: 500, def: 2000, level: 3, race: 'Beast', attribute: 'DARK', archetype: 'Danger!', banlist_info: { ban_tcg: 'Limited 1', ban_md: 'Limited 2' }, }, { id: 101111063, name: "Abyss Actors' Dress Rehearsal", type: 'Spell Card', desc: 'At the start of your Main Phase 1: Add 1 "Abyss Actor" card and 1 "Abyss Script" Spell from your Deck to your hand, also you cannot Pendulum Summon monsters for the rest of this turn after this card resolves, except "Abyss Actor" monsters.', race: 'Normal', archetype: 'Abyss Actor', } ]
你尝试的错误代码及报错
- 直接访问嵌套属性,因部分卡牌无
banlist_info报错:
filteredCards = await filteredCards.filter(o => o.banlist_info.ban_ocg === "Forbidden")
报错:
TypeError: Cannot read properties of undefined (reading 'ban_ocg')
- 错误地对
banlist_info对象使用数组filter方法:
filteredCards = await filteredCards.filter(o => o.banlist_info.filter(object => object.ban_ocg === "Forbidden"));
报错:
TypeError: Cannot read properties of undefined (reading 'filter')
- 错误地对
banlist_info对象使用数组some方法:
filteredCards = await filteredCards.filter(o => o.banlist_info.some(object => object.ban_ocg === "Forbidden"));
报错:
TypeError: Cannot read properties of undefined (reading 'some')
正确解决方案
核心是先判断banlist_info是否存在,再访问其ban_ocg属性,避免因属性缺失导致的报错。
方案1:使用可选链操作符(推荐,ES2020+支持)
可选链?.会在左侧值为undefined或null时直接返回undefined,不会继续访问后续属性:
filteredCards = filteredCards.filter(o => o.banlist_info?.ban_ocg === "Forbidden");
方案2:使用逻辑与短路判断(兼容旧环境)
通过&&短路特性,只有当banlist_info存在时,才会继续判断ban_ocg的值:
filteredCards = filteredCards.filter(o => o.banlist_info && o.banlist_info.ban_ocg === "Forbidden");
另外注意:Array.filter是同步方法,不需要加await,除非filteredCards本身是Promise,但通常卡牌数组是普通数组,直接调用filter即可。
内容的提问来源于stack exchange,提问作者Gleyveon
相关产品推荐
相关产品推荐

