I am trying to filter through this list of objects and only return the objects where the firstName starts with a specific value.
[
{"firstName":"Paul","lastName":"Collins"},
{"firstName":"Jerry","lastName":"Johnson"},
{"firstName":"Jody","lastName":"Johnson","occupation":"Occupado","company":"Companio"},
{"firstName":"Paul","lastName":"Johanson","occupation":"Developer","company":"Developer Co"}
]
The farthest I've gotten is this:
([].firstName | [?starts_with(@,'J') == `true`])
Which returns:
[
"Jerry",
"Jody"
]
However, I want to return whole objects that fit this condition, not just the firstName field. My desired output would be:
[
{"firstName":"Jerry","lastName":"Johnson"},
{"firstName":"Jody","lastName":"Johnson","occupation":"Occupado","company":"Companio"},
]
I couldn't find a way to pass an array of strings to starts_with
. I could get the values from the return and interpolate them into multiple queries one query with a bunch of "|| firstName == name1 || firstName == name2"
. However I am wanting to try to do this in one query string.
Any ideas?
CodePudding user response:
Use select( ... )
to filter a stream. By extension, you can use map( select( ... ) )
to remove items from an array.
map( select( .firstName | startswith("J") ) )
CodePudding user response:
In JMESPath, if that's what you are looking for, the filter projection can be applied on any property of an array, by simply specifying the said properties in the brackets selecting the array itself.
So, rather than going [].firstName
, the property comes inside the brackets, e.g. [?firstName == 'Jerry']
, would give you the whole object of the person named Jerry.
Then you can apply this using start_with()
:
[?starts_with(firstName,'J')]
Which will yield the expected
[
{
"firstName": "Jerry",
"lastName": "Johnson"
},
{
"firstName": "Jody",
"lastName": "Johnson",
"occupation": "Occupado",
"company": "Companio"
}
]