我有两个长度相同的数组,其中有对象:
input: [[{foo: 1}, {foo: 23}], [{bar: 12, baz: 543}, {bar: -1}]]
如何告诉jq将它们合并到一个数组中,如下所示?
output: [{foo: 1, bar: 12, baz: 543}, {foo: 23, bar: -1}]
答案 0 :(得分:3)
以下是使用transpose和add的解决方案。假设样本数据在data.json
:
$ jq -M 'transpose|map(add)' data.json
[
{
"foo": 1,
"bar": 12,
"baz": 543
},
{
"foo": 23,
"bar": -1
}
]
答案 1 :(得分:1)
以下是使用# Input: an array, padded as necessary with null.
# Output: a stream with |stream| items, `[$in[$i], $s$i] | f`,
# where $s$i is the $i-th item in the stream.
def zips(stream; f):
. as $in | foreach stream as $x (-1; .+=1; [$in[.], $x] | f);
定义的面向流的解决方案,其定义如下:
transpose
这可以避免zips
的开销,如果两个阵列尚未组合,或者流输出是可接受的,那么这将特别合适。
在任何情况下,. as $in
| $in[0] | [zips( $in[1][]; add )]
都可以按如下方式用于解决手头的问题:
zips
如果您不要求结果是单个数组,则可以省略对x= c(0, -1, -2, -3, -4, -5, -6, -7, -8)
y= c(-5.22672371336103, -2.04798328990208,
-0.998312848674327, -1.13656559451279, -1.80175393429754,
-2.67597356058193, -3.62933726371666, -4.61213085819315,
-5.60579419730348)
的调用的方括号。