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

如何用React Hooks将嵌套对象转换为分组选项数组

把API返回的嵌套对象转为分类选项数组

直接用JavaScript的Object.entries()结合数组方法就能实现,代码如下:

// API返回的原始数据
const apiResponse = {
    "category1": [
        {
            "categoryCode": "category1",
            "categoryLabel": "Vehicles",
            "code": "AAA",
            "label": "Car a"
        },
        {
            "categoryCode": "category1",
            "categoryLabel": "Vehicles",
            "code": "BBB",
            "label": "Car b"
        }
    ],
    "category2": [
        {
            "categoryCode": "category2",
            "categoryLabel": "Ship",
            "code": "CCC",
            "label": "Ship a"
        },
        {
            "categoryCode": "category2",
            "categoryLabel": "Ship",
            "code": "DDD",
            "label": "Ship b"
        },
        {
            "categoryCode": "category2",
            "categoryLabel": "Ship",
            "code": "EEE",
            "label": "Ship c"
        }
    ]
};

// 转换为目标格式
const options = Object.entries(apiResponse).map(([_, items]) => {
    return {
        label: items[0].categoryLabel,
        options: items.map(item => ({
            label: item.label,
            value: item.code
        }))
    };
});

console.log(options);

关键步骤说明

  1. 遍历对象键值对:Object.entries(apiResponse)把原始对象拆分为[分类标识, 对应子项数组]的键值对数组,方便后续遍历。
  2. 提取分类标签:同一分类下的子项categoryLabel是一致的,直接取数组第一个元素的该字段即可。
  3. 转换子项格式:用map()把每个子项转成{label: 显示文本, value: 对应值}的结构。
  4. 组合结果:把分类标签和转换后的子项数组组合成目标格式的对象,最终形成数组。

处理空分类的情况

如果API可能返回空分类(对应数组为空),可以先过滤掉这类数据:

const options = Object.entries(apiResponse)
    .filter(([_, items]) => items.length > 0)
    .map(([_, items]) => {
        return {
            label: items[0].categoryLabel,
            options: items.map(item => ({
                label: item.label,
                value: item.code
            }))
        };
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 14:46:01