[英]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.