Given an array of objects, I would like to inject a property with its position in the array. For example:
[ { "w" : "Hello" }, { "w" : "World } ]
I would like to produce:
[ { "w" : "Hello", p: 0 }, { "w" : "World, p:1 } ]
where p is the zero-based position in the array.
Is there a way to get the index of the element? I tried this but it is not working:
keys[] as $i | [ .[] | .p= $i ]
I get:
[ { "w" : "Hello", p: 0 }, { "w" : "World, p:0 } ]
You could do it like this:
[ keys[] as $i | .[$i] | .p=$i ]
Alternatively, you could make it work using to_entries like this:
[ to_entries[] | (.value.p=.key).value ]
Both of which yields:
[
{
"w": "Hello",
"p": 0
},
{
"w": "World",
"p": 1
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With