Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jq get array based on another array

I am using jq v1.5. Given the input:

{
    "mine": [
        "foo",
        "baz"
    ],
    "stuff": {
        "foo": {
            "name": "Foo"
        },
        "bar": {
            "name": "Bar"
        },
        "baz": {
            "name": "Baz"
        },
        "qux": {
            "name": "Qux"
        }
    }
}

How do I get all the .stuff.names for .mine?

For example, desired output:

[
    "Baz",
    "Foo"
]
like image 581
user1822391 Avatar asked Sep 02 '25 11:09

user1822391


1 Answers

Using a simple jq filter and no other shell processing, do it as below.

jq '[.mine[] as $in | .stuff[$in].name]'

The logic is basically index the values from .mine and for each entry get the equivalent .name value in .stuff

jqplay - URL

like image 123
Inian Avatar answered Sep 04 '25 00:09

Inian