I want to see if jq with js can help me to achieve the following:
I have the following object:
[
{
"a": 1,
"b": 2
},
{
"a": 11,
"b": 12
},
{
"a": 21,
"b": 22
}
]
and the following array:
[3,13,33,44]
I want to add the array items to the object according to their order as an extra field, it should also work when array is longer/shorter than the array of objects.
the result should look like this:
[
{
"a": 1,
"b": 2,
"c": 3
},
{
"a": 11,
"b": 12,
"c": 13
},
{
"a": 21,
"b": 22,
"c": 33
}
]
CodePudding user response:
Let's assume that you are interested in a jq solution, that the array of objects is in a file objects.json, and that you are willing to invoke jq along the following lines:
jq --argjson c '[3,13,33,44]' -f program.jq objects.json
Let's also assume for now that the result should NOT be lossy i.e., that the length of the resulting array should be the greater of the two input array lengths.
Then the following jq program will be of interest:
< objects.json jq --argjson c '[3,13,33,44]' '
({$c}|keys[0]) as $k
| [., ($c | map ( {($k): .} ))]
| transpose
| map(add)
'
Notice how the key name ("c") is derived from the parameter name on the command line.
There are various ways to trim the result so it has the length of the shorter of the two arrays, and it seems reasonable to leave that as an exercise.
CodePudding user response:
Using to_entries :
jq --argjson c '[4,13,33,44]'\
'to_entries|
map(
.value (if .key<($c|length) then {c:$c[.key]} else {} end)
)' objects.json
