如何用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);
关键步骤说明
- 遍历对象键值对:
Object.entries(apiResponse)把原始对象拆分为[分类标识, 对应子项数组]的键值对数组,方便后续遍历。 - 提取分类标签:同一分类下的子项
categoryLabel是一致的,直接取数组第一个元素的该字段即可。 - 转换子项格式:用
map()把每个子项转成{label: 显示文本, value: 对应值}的结构。 - 组合结果:把分类标签和转换后的子项数组组合成目标格式的对象,最终形成数组。
处理空分类的情况
如果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
相关产品推荐
相关产品推荐

