[英]How to group by a field in an object to create an array of objects?
我有一個包含對象數組的輸入有效負載,我需要在其中按id-key進行group-by
id-key 形成 2 arrays 對象。 請參閱下面的詳細信息。
輸入有效載荷:
{
"id": {
"header_id": "460",
"id-branch": {
"branch-name": "genaral motors",
"req-name": "genaral motors",
"id-key": "0791",
"id-lines": {
"id-key": "0791",
"productId": "463"
}
},
"id-branch": {
"branch-name": "genaral motors",
"req-name": "genaral motors",
"id-key": "9692",
"id-lines": {
"id-key": "9692",
"productId": "464"
},
"id-lines": {
"id-key": "9692",
"productId": "465"
}
}
}
}
所需的輸出:
[
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"type": "dhl",
"lines-ids": "swr",
"lines": [
{
"productId": "463"
}
]
},
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"type": "dhl",
"lines-ids": "swr",
"lines": [
{
"productId": "464"
},
{
"productId": "465"
}
]
}
]
output 必須生成為 object 的數組,該數組將productId分組在相同的 id-key 下。
假設鍵已經按產品 ID 分組,我使用 filterObject() 刪除不需要的鍵,然后使用 pluck() 將值選取到數組中。 之后,我從每個元素中刪除了 output 中未使用的鍵。添加的鍵我假設是文字,因為沒有給出任何指示。 為了清楚起見,我實現了一個 function 來封裝線路的映射。
%dw 2.0
output application/json
fun updateLines(x)=
x - "id-lines" ++ {lines: x.*"id-lines" map {productId: $.productId}}
---
payload.id
filterObject ((value, key, index) -> key as String == "id-branch")
pluck ($)
map (updateLines($) - "id-key" ++ { "type": "dhl", "lines-ids": "swr"})
Output:
[
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"lines": [
{
"productId": "463"
}
],
"type": "dhl",
"lines-ids": "swr"
},
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"lines": [
{
"productId": "464"
},
{
"productId": "465"
}
],
"type": "dhl",
"lines-ids": "swr"
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.