From e2cbec17bfb9baa391af1621110069e0342f95eb Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 20 Jan 2023 09:36:08 -0600 Subject: [PATCH] Add Find All Objects With A Matching Key Value Pair as a jq TIL --- README.md | 3 +- ...-objects-with-a-matching-key-value-pair.md | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 jq/find-all-objects-with-a-matching-key-value-pair.md diff --git a/README.md b/README.md index 4dd8432..221ee02 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1274 TILs and counting..._ +_1275 TILs and counting..._ --- @@ -478,6 +478,7 @@ _1274 TILs and counting..._ ### jq - [Extract A List Of Values](jq/extract-a-list-of-values.md) +- [Find All Objects With A Matching Key Value Pair](jq/find-all-objects-with-a-matching-key-value-pair.md) - [Reduce Object To Just Entries Of A Specific Type](jq/reduce-object-to-just-entries-of-a-specific-type.md) ### Kitty diff --git a/jq/find-all-objects-with-a-matching-key-value-pair.md b/jq/find-all-objects-with-a-matching-key-value-pair.md new file mode 100644 index 0000000..7954cdf --- /dev/null +++ b/jq/find-all-objects-with-a-matching-key-value-pair.md @@ -0,0 +1,45 @@ +# Find All Objects With A Matching Key Value Pair + +Let's say I have a JSON file representing a bunch of people's reading lists. +That means it is an array of objects where each object is a person's reading +profile and contains a _list_ of books. Some of those books have a _status_ of +`reading` meaning the person is currently reading that book. + +How can we find all books that are currently being read? + +``` +jq '. | map( + { + name: .username, + in_progress_books: (.books | map(select(.status == "reading"))) + } + )' +``` + +``` +[ + { name: 'bobr', in_progress_books: [...] }, + { name: 'sallyf', in_progress_books: [...] }, + ... +] +``` + +That will show us for each reader what books they are currently reading. + +Alternatively, we could roll that all up into a single list of books. + +``` +jq '. | + map(.books | map(select(.status == "reading"))) | + flatten' +``` + +``` +[ + { title: 'Moby Dick', status: 'reading', ... } + { title: 'The Great Gatsby', status: 'reading', ... } + ... +] +``` + +[source](https://stackoverflow.com/a/18608100/535590)