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

使用jq展开含数组的对象:为嵌套数组每项生成新对象

实现类似Mongo $unwind/BigQuery UNNEST的数组展开操作

你描述的这个操作就是典型的数组展开(Unnest/Unwind),和MongoDB聚合中的$unwind、BigQuery的UNNEST行为完全一致——将包含数组的对象拆分为多条记录,每条记录对应数组中的一个元素,同时保留原对象的其他非数组字段。

原始JSON结构

[
  {
    "root-array-a": [
      11,
      12,
      13
    ],
    "root-property-b": 22,
    "root-property-c": 33
  }
]

期望结果

[
  {
    "root-property-a": 11,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 12,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 13,
    "root-property-b": 22,
    "root-property-c": 33
  }
]

示例实现(JavaScript)

如果用JavaScript实现这个逻辑,可以通过遍历拆分数组来完成:

const originalData = [
  {
    "root-array-a": [11, 12, 13],
    "root-property-b": 22,
    "root-property-c": 33
  }
];

const result = originalData.flatMap(item => {
  const { "root-array-a": arrayA, ...rest } = item;
  return arrayA.map(num => ({
    "root-property-a": num,
    ...rest
  }));
});

console.log(JSON.stringify(result, null, 2));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:50:20