基于属性匹配过滤映射对象:生成名称与游戏名对应结构
问题解决:根据类型匹配生成游戏列表结构
需求说明
基于给定数据,需执行过滤与映射操作:当otherTypes的键与types中对象的number数组内的值匹配时,生成以otherTypes里的name为键、对应匹配到的nameOfGame数组为值的结构。使用includes方法时遇到问题。
期望输出(注:实际应为对象而非数组,数组不支持自定义键名)
{ name1: ['game1'], name2: ['game2', 'game3'], name3: [] }
原始数据
const data = { types: [ { nameOfGame: 'game1', number: [1] }, { nameOfGame: 'game2', number: [3] }, { nameOfGame: 'game3', number: [3] } ], otherTypes: { 1: { name: 'name1' }, 3: { name: 'name2' }, 5: { name: 'name3' } } };
解决代码
// 将otherTypes的键值对转为数组,方便遍历处理 const otherTypesEntries = Object.entries(data.otherTypes); // 用reduce聚合生成目标结构 const result = otherTypesEntries.reduce((acc, [numKey, { name }]) => { // 筛选出number数组包含当前numKey的游戏项,注意类型转换 const matchedGames = data.types .filter(item => item.number.includes(Number(numKey))) .map(item => item.nameOfGame); acc[name] = matchedGames; return acc; }, {}); console.log(result);
关键细节
- 类型匹配问题:
otherTypes的键是字符串类型(比如"1"),而types里的number存储的是数字,必须用Number(numKey)转换后再调用includes,这大概率是你之前出错的核心原因。 - 自动处理空数组:如果没有匹配到对应游戏,
filter会返回空数组,直接赋值就能满足name3: []的需求。 - 遍历逻辑:用
reduce遍历otherTypes的所有条目,逐个完成匹配和赋值,最终得到目标对象。
内容的提问来源于stack exchange,提问作者Arssin
相关产品推荐
相关产品推荐

