JavaScript:根据嵌套数组的color属性整理动物对象数组
按动物颜色将嵌套数组整理为映射结构
我有一个嵌套的animals对象数组,需要根据动物的color属性把它整理成以颜色为键的映射结构。
原始数据
const animals = [ { type: 'dog', species: [ { name: 'retriever', color: 'yellow', }, { name: 'pug', color: 'black', }, { name: 'lab', color: 'white', }, ], }, { type: 'cat', species: [ { name: 'persian', color: 'white', }, { name: 'shorthair', color: 'black', }, ], }, ];
期望输出
const animalsByColor = { black: [ { type: 'dog', species: [ { name: 'pug', color: 'black', }, ], }, { type: 'cat', species: [ { name: 'shorthair', color: 'black', }, ], }, ], white: [ { type: 'dog', species: [ { name: 'lab', color: 'white', }, ], }, { type: 'cat', species: [ { name: 'persian', color: 'white', }, ], }, ], yellow: [ { type: 'dog', species: [ { name: 'retriever', color: 'yellow', }, ], }, ], };
解决方案
通过遍历原始数组拆分不同颜色的物种,再按颜色归类即可实现需求:
function groupAnimalsByColor(animals) { const result = {}; animals.forEach(animalType => { animalType.species.forEach(species => { const color = species.color; // 初始化当前颜色对应的数组 if (!result[color]) { result[color] = []; } // 构造对应颜色的动物类型条目 const entry = { type: animalType.type, species: [species] }; result[color].push(entry); }); }); return result; } // 使用示例 const animalsByColor = groupAnimalsByColor(animals);
思路说明
- 初始化空对象
result作为最终映射容器。 - 外层遍历每个动物类型(如
dog、cat)。 - 内层遍历该类型下的每个物种,提取
color作为映射的键。 - 若该颜色未在
result中存在,先创建对应的空数组。 - 构造包含当前动物类型和单一物种的对象,添加到对应颜色的数组中。
- 遍历完成后返回
result,得到目标结构。
内容的提问来源于stack exchange,提问作者thereallj
相关产品推荐
相关产品推荐

