如何使用 jq 将数组中对象的数组索引注入到对象中
How to inject the array indices of objects in an array into the objects, using jq
给定一个对象数组,我想注入一个 属性 及其在数组中的位置。
例如:
[ { "w" : "Hello" }, { "w" : "World } ]
我要制作:
[ { "w" : "Hello", p: 0 }, { "w" : "World, p:1 } ]
其中 p 是数组中从零开始的位置。
有没有办法获取元素的索引?
我试过了,但没有用:
keys[] as $i | [ .[] | .p= $i ]
我得到:
[ { "w" : "Hello", p: 0 }, { "w" : "World, p:0 } ]
你可以这样做:
[ keys[] as $i | .[$i] | .p=$i ]
或者,您可以像这样使用 to_entries
使其工作:
[ to_entries[] | (.value.p=.key).value ]
两者都产生:
[
{
"w": "Hello",
"p": 0
},
{
"w": "World",
"p": 1
}
]
这是一个使用 reduce
的解决方案
reduce keys[] as $i (.; .[$i].p = $i)
给定一个对象数组,我想注入一个 属性 及其在数组中的位置。 例如:
[ { "w" : "Hello" }, { "w" : "World } ]
我要制作:
[ { "w" : "Hello", p: 0 }, { "w" : "World, p:1 } ]
其中 p 是数组中从零开始的位置。
有没有办法获取元素的索引? 我试过了,但没有用:
keys[] as $i | [ .[] | .p= $i ]
我得到:
[ { "w" : "Hello", p: 0 }, { "w" : "World, p:0 } ]
你可以这样做:
[ keys[] as $i | .[$i] | .p=$i ]
或者,您可以像这样使用 to_entries
使其工作:
[ to_entries[] | (.value.p=.key).value ]
两者都产生:
[
{
"w": "Hello",
"p": 0
},
{
"w": "World",
"p": 1
}
]
这是一个使用 reduce
reduce keys[] as $i (.; .[$i].p = $i)