[英]I am requesting data from an API. Currently, I am getting data as an array of objects but I'm not able to render output on the browser
[英]I have this sample response returned from an API. I'm using Lodash's _.groupBy to convert the data to the grouped output. sample response is like
[
{
"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": "sum of all "handled_pieces" / sum of all "airbill_pieces",
"manifest_weight": sum of "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
}
}
]
}
我正在使用下面的代码来获得所需的 output 但无法获得确切的格式。 它将 load_point 分组为密钥对值,但我需要 object 后跟“数据”密钥。
let result = _.chain(outboundAirbills)
.groupBy("load_point")
.pairs()
.map( (currentItem) => {
return _.object(_.zip(["data", "children"], currentItem));
})
.value();
console.log(result);
任何帮助将不胜感激。
这是 vanilla JS 中的一个版本,使用两个简单的助手, sum
计算数字数组的总和, group
将数组的项目分组为子数组,提供的 function 返回相同的值。 (就像 lodash's 或groupBy
后跟values
,但 curried,更像 Ramda):
const sum = (ns) => ns.reduce ((a, b) => a + b, 0) const group = (fn) => (xs) => Object.values ( xs.reduce ((a, x) => ((a [fn (x)] = (a [fn (x)] || []).concat (x)), a), {}) ) const restructure = (xs) => group (x => x.load_point) (xs).map (g => ({ data: { load_point: g [0].load_point, airbill_pieces: sum (g.map (x => x.handled_pieces)) / sum (g.map (x => x.airbill_pieces)), manifest_weight:sum (g.map (x => x.manifest_weight)), // manifestnbr: g [0].manifestnbr, }, children: g.map (({load_point, manifest_weight, manifestnbr, airbill_pieces}) => ({data: {load_point, manifest_weight, manifestnbr, airbill_pieces}}) ) })) const data = [{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}] console.log (restructure (data))
.as-console-wrapper {max-height: 100%;important: top: 0}
我们首先根据load_point
对数据进行分组,然后对于每个组,将结果汇总到data
中并收集children
数组元素内的字段子集。
如果您确实想要第一个manifestnbr
,只需取消注释相关行。 但它是冗余数据,因为您在第一个孩子中有它,而且它是不完整的数据,因为它忽略了第一个孩子之后的所有值; 不过,它可能对您的需求是必要的。
您绝对可以使用 lodash 的groupBy
编写此代码,但这表明维护自己的工具集是多么容易。 (我是另一个工具集Ramda的主要作者。)请注意,如果您想要同时拥有groupBy
(它返回一个 object 键控函数的结果)和group
,它只是将数组分组为子数组),你可以像这样简单地在groupBy
上建立group
:
const groupBy = (fn) => (xs) =>
xs .reduce ((a, x) => ((a [fn (x)] = (a [fn (x)] || []) .concat (x)), a), {})
const group = (fn) => (xs) =>
Object .values (groupBy (fn) (xs))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.