使用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
相关产品推荐
相关产品推荐

