简体   繁体   English

如何按 object 中的字段分组以创建对象数组?

[英]How to group by a field in an object to create an array of objects?

I have an input payload containing array of objects where I need to group-by id-key and form 2 arrays of objects based on id-key.我有一个包含对象数组的输入有效负载,我需要在其中按id-key进行group-by id-key 形成 2 arrays 对象。 See below details.请参阅下面的详细信息。

input Payload :输入有效载荷

{
  "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"
      }
    }
  }
}

desired Ouput :所需的输出

[                      
 {
  "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"
    }
  ]
 }
]

the output has to be generated as array of object which groups productId which are under same id-key. output 必须生成为 object 的数组,该数组将productId分组在相同的 id-key 下。

Assuming that the keys are already grouped by product id, I used filterObject() to remove the keys that are not required, then use pluck() to pick the values into an array.假设键已经按产品 ID 分组,我使用 filterObject() 删除不需要的键,然后使用 pluck() 将值选取到数组中。 After that I removed keys from each element that are not used in the output. The keys added I assumed that were literal since no indication was given.之后,我从每个元素中删除了 output 中未使用的键。添加的键我假设是文字,因为没有给出任何指示。 For clarity I implemented a function to encapsulate the mapping of the lines.为了清楚起见,我实现了一个 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: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM