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

如何使用JSONata按类型对电话号码对象数组分组

问题:将电话号码数组按类型分组为指定结构

原始输入数据:

{"Phone": [{"type": "home","number": "0203 544 1234"},{"type": "office","number": "01962 001234"},{"type": "office","number": "01962 001235"},{"type": "mobile","number": "077 7700 1234"}]}

期望输出结构:

[{"type": "home","numbers": ["0203 544 1234"]},{"type": "office","numbers": ["01962 001234","01962 001235"]},{"type": "mobile","numbers": ["077 7700 1234"]}]

尝试过的JSONata表达式及不符合预期的结果:
表达式:Phone{type: number}
结果:

{"home": "0203 544 1234","office": ["01962 001234","01962 001235"],"mobile": "077 7700 1234"}

解决方案

使用以下JSONata表达式即可得到目标结构:

Phone{type: $collect(number)} ~> $each(function($numbers, $type) {
  {"type": $type, "numbers": $numbers}
})

说明

  1. Phone{type: $collect(number)}:先按type字段分组,通过$collect()确保所有类型对应的号码都以数组形式存储(避免单个号码时返回字符串),得到键为类型、值为号码数组的对象。
  2. ~> $each(...):遍历分组后的对象,将每个键值对转换为包含type(键名)和numbers(键值数组)的对象,最终组合成目标数组。

也可以用更简洁的写法:

$map(Phone{type: $collect(number)}, function($v, $k) {
  {"type": $k, "numbers": $v}
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:38:25