1

是否可以通过 JSONata 按特定属性对项目进行分组

例如,按照 resultDate 的值对 json 进行分组。

"Export": [
  {
    "code": "18724-100",
    "resultDate": "11.03.2018 13:11:48"
  },
  {
    "code": "18724-5",
    "resultDate": "11.03.2018 13:11:48"
  },
  {
    "code": "18724-99",
    "resultDate": "14.03.2018 14:11:48"
  }
]

要生成以下输出:

"Export": [
  {
    "resultDate": "11.03.2018 13:11:48",
    "codes": [
      {
        "code": "18724-100"
      },
      {
        "code": "18724-5"
      }
    ]
  },
  {
    "resultDate": "14.03.2018 13:11:48",
    "codes": [
      {
        "code": "18724-99"
      }
    ]
  }
]

也许使用 reduce 函数将元素分组,如本博文中所述。https://www.datchley.name/getting-functional-with-javascript-part-2/

4

3 回答 3

2

每当我需要按公共属性(如resultDate)对某些对象进行分组时,我会使用该属性的值作为键创建一个对象,并从每个原始对象中删除该属性。然后我使用该$spread()函数将该大对象拆分为一个对象数组,每个对象都有一个属性。最后一步是用原始属性名称替换每个对象的第一个(也是唯一一个)键。

The JSONata expression to do this is a bit convoluted:

{
    "Export": $spread(Export {
        resultDate: [
            $ ~> | $ | {}, "resultDate" |
        ]
    }).{
        "resultDate": $keys()[0],
        "codes": *
    }
}

You can try it for yourself by going to this exerciser link.

于 2018-06-05T16:43:46.177 回答
2

The following expression can be used for this:

{
  "Export": Export{resultDate: code[]} ~> $each(function($v, $k) {
    {
      "resultDate": $k,
      "codes": $v.{"code": $}
    }
  })
}

The first part Export{resultDate: code[]} groups the data by resultDate then the $each function iterates over the name/value pairs to produce the output. Expressions like this will probably be easier once the $distinct function is added to the language (https://github.com/jsonata-js/jsonata/issues/117)

于 2018-06-06T07:13:24.277 回答
1

Yet another way of grouping in general is:

  1. create the resulting structure with the key to group by
  2. take the array of values thereafter

PS. I like Andrew Coleman answer better though

So for this question, that would go like:

${
    resultDate: {
        "resultDate": $distinct(resultDate),
        "codes": code.{"code": $}
    }
} ~> $each(function($v){$v})
于 2020-10-19T12:48:53.873 回答