Jq: group and key by property

I have a list of objects that look like this:

[ { "ip": "1.1.1.1", "component": "name1" }, { "ip": "1.1.1.2", "component": "name1" }, { "ip": "1.1.1.3", "component": "name2" }, { "ip": "1.1.1.4", "component": "name2" } ] 

Now I would like to group and indicate this by the component and assign an ips list for each of the components:

 { "name1": [ "1.1.1.1", "1.1.1.2" ] },{ "name2": [ "1.1.1.3", "1.1.1.4" ] } 
+5
source share
1 answer

I figured it out myself. I first group .component and then just create new ips lists that are indexed by the component of the first object of each group:

jq ' group_by(.component)[] | {(.[0].component): [.[] | .ip]}'

+6
source

Source: https://habr.com/ru/post/1266337/


All Articles