You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSONata将数组转换为指定结构的对象?

JSONata数组按类型分组转换问题

输入数据

$array := [
  {
    "thing": "one",
    "stuff": {
      "type": "car",
      "engine": "vrooom"
    }
  },
  {
    "thing": "two",
    "stuff": {
      "type": "truck",
      "engine": "vrooom"
    }
  },
  {
      "thing": "three",
      "stuff": {
          "type": "car",
          "engine": "vroom"
      }
  }
];

期望输出

{
  "car": [
    {
      "thing": "one",
      "stuff": {
        "type": "car",
        "engine": "vroom"
      }
    },
    {
      "thing": "three",
      "stuff": {
        "type": "car",
        "engine": "vroom"
      }
    }
  ],
  "truck": [
    {
      "thing": "two",
      "stuff": {
        "type": "truck",
        "engine": "vrooom"
      }
    }
  ]
}

尝试的代码及问题

尝试用$reduce实现分组,但输出出现重复数据:

$reduce($array, function($accumulator, $value, $index){ 
  $merge([$accumulator, {$value.stuff.type: [$accumulator.$value, $value]}]) 
}, {} )

错误输出:

{
  "car": [
    {
      "thing": "three",
      "stuff": {
        "type": "car",
        "engine": "vroom"
      }
    },
    {
      "thing": "three",
      "stuff": {
        "type": "car",
        "engine": "vroom"
      }
    }
  ],
  "truck": [
    {
      "thing": "two",
      "stuff": {
        "type": "truck",
        "engine": "vrooom"
      }
    },
    {
      "thing": "two",
      "stuff": {
        "type": "truck",
        "engine": "vrooom"
      }
    }
  ]
}

问题核心是$accumulator.$value语法错误——累加器对象中不存在$value属性,无法正确获取同类型的已有数组,导致每次迭代都错误地重复添加当前项。

修正方案

方法1:修正$reduce逻辑

每次迭代时,先取出累加器中当前类型对应的已有数组(不存在则为空数组),再将当前项追加到该数组,最后合并回累加器:

$reduce($array, function($acc, $val) {
  $merge([
    $acc,
    {
      $val.stuff.type: ($acc[$val.stuff.type] ? $acc[$val.stuff.type] & [$val] : [$val])
    }
  ])
}, {})

方法2:使用内置$groupBy函数(更简洁)

JSONata提供了专门的分组函数$groupBy,无需手动实现$reduce逻辑:

$groupBy($array, function($item) { $item.stuff.type })

两种方式均可得到符合预期的分组结果。

内容的提问来源于stack exchange,提问作者Matt Coady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:05:52