使用Lodash的_.groupBy处理API数据时格式不符的问题求助
问题:将API返回数据转换为指定嵌套结构
API返回示例数据
[ { "airbill_pieces": 1, "airbillnbr": 81061140, "load_point": "IND", "manifestnbr": 1907521, "handled_pieces": 5, "manifest_weight": 12548 }, { "airbill_pieces": 2, "airbillnbr": 81061158, "load_point": "IND", "manifestnbr": 1907522, "handled_pieces": 12, "manifest_weight": 12368 } ]
目标格式
{ "data": { "load_point": "IND", "airbill_pieces": "所有handled_pieces总和 / 所有airbill_pieces总和", "manifest_weight": 所有manifest_weight总和, "manifestnbr": 1907521 }, "children": [ { "data": { "airbillnbr": 81061140, "manifest_weight": 12548, "manifestnbr": 1907521, "airbill_pieces": 1 } }, { "data": { "airbillnbr": 81061158, "manifest_weight": 12368, "manifestnbr": 1907522, "airbill_pieces": 2 } } ] }
现有代码及问题
当前使用的Lodash代码无法生成符合要求的结构,代码如下:
let result = _.chain(outboundAirbills) .groupBy("load_point") .pairs() .map( (currentItem) => { return _.object(_.zip(["data", "children"], currentItem)); }) .value(); console.log(result);
问题:代码将load_point作为键值对分组,无法生成包含data键的嵌套对象结构。
解决方案
调整后的代码会遍历分组后的数据,手动构建data和children结构,同时计算所需的汇总值:
let result = _.chain(outboundAirbills) .groupBy("load_point") .map((groupItems, loadPoint) => { // 计算各类总和 const totalHandledPieces = _.sumBy(groupItems, "handled_pieces"); const totalAirbillPieces = _.sumBy(groupItems, "airbill_pieces"); const totalManifestWeight = _.sumBy(groupItems, "manifest_weight"); // 构建children数组的明细项 const children = groupItems.map(item => ({ data: { airbillnbr: item.airbillnbr, manifest_weight: item.manifest_weight, manifestnbr: item.manifestnbr, airbill_pieces: item.airbill_pieces } })); // 组装最终的分组对象 return { data: { load_point: loadPoint, airbill_pieces: `${totalHandledPieces} / ${totalAirbillPieces}`, manifest_weight: totalManifestWeight, manifestnbr: groupItems[0].manifestnbr // 取分组内第一个项的manifestnbr }, children: children }; }) .value(); console.log(result);
代码说明
- 保留
groupBy("load_point")的分组逻辑,按load_point聚合数据 - 使用
sumBy方法计算handled_pieces、airbill_pieces和manifest_weight的总和 - 遍历分组内的每个数据项,构建
children数组中包含data键的明细结构,只保留目标格式所需字段 - 最终组装包含汇总信息的
data对象和明细项的children数组,完全匹配目标格式要求
内容的提问来源于stack exchange,提问作者Rahul kumar dhiman
相关产品推荐
相关产品推荐

