如何用纯JavaScript按Location、Item ID嵌套分组库存对象数组?
问题描述
现有包含5列数据的数据集,列名分别为Location、Item ID、Inventory Number、Bin Number、Quantity,示例数据如下:
[ { "Item ID": 12, "Location": "DEL", "Inventory Number": 18, "Bin Number": 3, "Quantity": 250 }, { "Item ID": 22, "Location": "DEL", "Inventory Number": 30, "Bin Number": 3, "Quantity": 50 }, { "Item ID": 12, "Location": "DEL", "Inventory Number": 19, "Bin Number": 3, "Quantity": 250 }, { "Item ID": 22, "Location": "DEL", "Inventory Number": 31, "Bin Number": 3, "Quantity": 50 } ]
需要按以下规则处理数据:
- 先按
Location分组 - 每个
Location下再按Item ID分组 - 为每个唯一
Item ID整理对应Inventory Number的相关数据,最终得到如下格式的结果:
{ "DEL": [ { "itemId": "12", "quantity": "500", "bins": [ { "inventorynumber": "18", "binnumber": "3", "quantity": "250" }, { "inventorynumber": "19", "binnumber": "3", "quantity": "250" } ] }, { "itemId": "22", "quantity": "100", "bins": [ { "inventorynumber": "30", "binnumber": "3", "quantity": "50" }, { "inventorynumber": "31", "binnumber": "3", "quantity": "50" } ] } ] }
需用纯JavaScript实现该需求,目前能单独完成各层分组,但无法得到指定的嵌套格式。
解决方案
可以通过两次分组+格式转换来实现目标结构,核心思路是先按Location和Item ID组合键聚合数据,再逐层整理成要求的嵌套格式:
const rawData = [ { "Item ID": 12, "Location": "DEL", "Inventory Number": 18, "Bin Number": 3, "Quantity": 250 }, { "Item ID": 22, "Location": "DEL", "Inventory Number": 30, "Bin Number": 3, "Quantity": 50 }, { "Item ID": 12, "Location": "DEL", "Inventory Number": 19, "Bin Number": 3, "Quantity": 250 }, { "Item ID": 22, "Location": "DEL", "Inventory Number": 31, "Bin Number": 3, "Quantity": 50 } ]; function transformInventoryData(data) { // 第一步:按 Location + Item ID 组合键聚合数据,收集总数量和bin详情 const groupedByLocAndItem = data.reduce((acc, item) => { const key = `${item.Location}-${item["Item ID"]}`; if (!acc[key]) { acc[key] = { location: item.Location, itemId: item["Item ID"], totalQuantity: 0, bins: [] }; } acc[key].totalQuantity += item.Quantity; acc[key].bins.push({ inventorynumber: item["Inventory Number"].toString(), binnumber: item["Bin Number"].toString(), quantity: item.Quantity.toString() }); return acc; }, {}); // 第二步:将聚合数据转换为按Location嵌套的最终格式 const result = Object.values(groupedByLocAndItem).reduce((acc, group) => { if (!acc[group.location]) { acc[group.location] = []; } acc[group.location].push({ itemId: group.itemId.toString(), quantity: group.totalQuantity.toString(), bins: group.bins }); return acc; }, {}); return result; } // 调用并输出结果 const transformedData = transformInventoryData(rawData); console.log(JSON.stringify(transformedData, null, 2));
代码说明:
- 第一层聚合:用
reduce遍历原始数据,以Location-Item ID作为唯一标识,把同一位置同一商品的条目合并,同时累加总数量、收集每个库存项的bin详情。 - 第二层转换:再次使用
reduce,将聚合后的数据按Location分组,整理成目标要求的嵌套数组结构,同时将所有数值转为字符串(匹配示例结果格式)。 - 代码支持多Location、多Item ID的通用场景,无需针对单一数据结构硬编码。
内容的提问来源于stack exchange,提问作者Shubhan
相关产品推荐
相关产品推荐

