You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

思路说明

  1. 初始化空对象result作为最终映射容器。
  2. 外层遍历每个动物类型(如dog、cat)。
  3. 内层遍历该类型下的每个物种,提取color作为映射的键。
  4. 若该颜色未在result中存在,先创建对应的空数组。
  5. 构造包含当前动物类型和单一物种的对象,添加到对应颜色的数组中。
  6. 遍历完成后返回result,得到目标结构。

内容的提问来源于stack exchange,提问作者thereallj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:40:34