如何在JavaScript中对扁平化数组实现分类-子分类-商品层级分组?
问题描述
现有扁平化JavaScript数组:
[{ "category": "FRESH MEAT NON PI", "categoryId": 76, "subCategoryId": 12, "subCategory": "BEEF-THIN MEATS", "itemThreshold": null, "sellItem": "BEEF SHORT RIBS", "sellItemId": 980217310, "key": "76-12" }, { "category": "FRESH MEAT NON PI", "categoryId": 76, "subCategoryId": 12, "subCategory": "BEEF-THIN MEATS", "itemThreshold": null, "sellItem": "BEEF T-BONE STEAK", "sellItemId": 12049, "key": "76-12" }]
需要转换为如下层级结构数组:
[ { "id": 76, "categoryName": "FRESH MEAT NON PI", "categoryThreshold": null, "subCategories": [ { "id": 12, "key": "76-12", "name": "BEEF-THIN MEATS", "subCategoryThreshold": null, "sellitems": [ { "id": 980217310, "name": "BEEF SHORT RIBS", "itemThreshold": null, "edited": false, "rowId": 1 }, { "id": 12049, "name": "BEEF T-BONE STEAK", "itemThreshold": null, "edited": false, "rowId": 2 } ] } ] } ]
已尝试使用reduce方法分组,但还未实现将sellitems嵌套到subCategories中,现有代码:
const out = Object.values(data.reduce((acc, current) => { // Destructure the properies from the current object const { categoryId, subCategory, ...rest } = current; acc[categoryId] = acc[categoryId] || { categoryId, subCategory: [], ...rest }; acc[categoryId].subCategory.push(subCategory); // Return the accumulator for the next iteration return acc; }, {}));
请问如何实现目标层级结构?
解决方案
要实现分类→子分类→商品的三级嵌套,需要在reduce中逐层处理分组逻辑,具体步骤如下:
- 分类层级处理:按
categoryId判断是否已存在该分类,不存在则初始化符合目标结构的分类对象。 - 子分类层级处理:在当前分类的
subCategories数组中,按subCategoryId查找对应子分类,不存在则初始化子分类对象并推入数组。 - 商品层级处理:将当前项转换为目标结构的商品对象,添加到对应子分类的
sellitems数组中。
完整代码示例:
const data = [/* 你的扁平化数组数据 */]; const result = Object.values(data.reduce((acc, item) => { // 1. 初始化或获取当前分类 const categoryKey = item.categoryId; if (!acc[categoryKey]) { acc[categoryKey] = { id: item.categoryId, categoryName: item.category, categoryThreshold: null, // 原数据无对应值,设为默认null subCategories: [] }; } const currentCategory = acc[categoryKey]; // 2. 初始化或获取当前子分类 const subCategoryKey = item.subCategoryId; let currentSubCategory = currentCategory.subCategories.find(sc => sc.id === subCategoryKey); if (!currentSubCategory) { currentSubCategory = { id: item.subCategoryId, key: item.key, name: item.subCategory, subCategoryThreshold: null, // 原数据无对应值,设为默认null sellitems: [] }; currentCategory.subCategories.push(currentSubCategory); } // 3. 转换并添加商品到子分类 const sellItem = { id: item.sellItemId, name: item.sellItem, itemThreshold: item.itemThreshold, edited: false, // 原数据无对应值,设为默认false rowId: currentSubCategory.sellitems.length + 1 // 自动生成递增rowId }; currentSubCategory.sellitems.push(sellItem); return acc; }, {})); console.log(result);
代码说明
- 分类初始化:仅在首次遇到该分类ID时创建,避免重复生成。
- 子分类查找:通过
find方法快速定位已存在的子分类,提升效率。 - 字段映射:严格对应目标结构的字段名,原数据缺失的字段按需求设置默认值(如
edited、rowId)。
内容的提问来源于stack exchange,提问作者karan deep
相关产品推荐
相关产品推荐

