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

jq查询问题:合并JOIN匹配结果而非仅保留最后匹配项

解决jq中合并多个thingGroup对应things数组的问题

问题描述

执行以下jq查询时:

{places: [JOIN(INDEX(.thingGroups[]; .thingGroup); .places[]; .thingGroup[] // empty; add)]}

针对目标数据,发现location为wwc3和wwc4的条目仅保留了最后一个thingGroup(rs)对应的things数组,而非合并所有匹配thingGroup的结果。同时需要满足:

  • 无thingGroup的条目(如wwc1)原样输出
  • 原数据中的其他字段(如fStuff)保持不变

解决方案

使用以下jq脚本:

(INDEX(.thingGroups[]; .thingGroup) as $index)
| .places |= map(
  if has("thingGroup") then
    . + {things: [.thingGroup[] as $tg | $index[$tg].things[]]}
  else . end
)

脚本说明

  1. 构建索引:通过INDEX(.thingGroups[]; .thingGroup)将thingGroups数组转换为以thingGroup名称为键的对象索引,实现对对应things数组的快速查找。
  2. 处理places数组:
    • 遍历每个place条目,用has("thingGroup")判断是否包含目标字段
    • 若包含,遍历该条目的thingGroup数组,从索引中取出每个thingGroup对应的things元素,合并为一个新数组后与原条目合并(保留原有thingGroup数组及其他字段)
    • 若不包含,直接保留原条目
  3. 保留原数据结构:通过.places |= ...仅更新places字段,原数据中的其他字段(如fStuff)不受任何改动。

执行结果

处理后wwc3和wwc4的条目会合并对应thingGroup的things数组:

{
  "location": "wwc3",
  "thingGroup": [
    "bs-3",
    "rs"
  ],
  "things": [
    "ci",
    "co",
    "dq",
    "cust"
  ]
},
{
  "location": "wwc4",
  "thingGroup": [
    "bs-4",
    "rs"
  ],
  "things": [
    "ems",
    "erec",
    "home",
    "cust"
  ]
}

无thingGroup的wwc1条目原样保留,fStuff字段也保持初始状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:58:16