From 66fd1e6c19a0df2f8f1729787ac7d4a62ad0dd2c Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 17 Aug 2023 10:14:00 -0500 Subject: [PATCH] Add Combine An Array Of Objects Into A Single Object as a jq TIL --- README.md | 3 +- ...n-array-of-objects-into-a-single-object.md | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 jq/combine-an-array-of-objects-into-a-single-object.md diff --git a/README.md b/README.md index a6b9668..17d77ba 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). -_1332 TILs and counting..._ +_1333 TILs and counting..._ --- @@ -492,6 +492,7 @@ _1332 TILs and counting..._ ### jq +- [Combine An Array Of Objects Into A Single Object](jq/combine-an-array-of-objects-into-a-single-object.md) - [Count Each Collection In A JSON Object](jq/count-each-collection-in-a-json-object.md) - [Count The Number Of Things In A JSON File](jq/count-the-number-of-things-in-a-json-file.md) - [Extract A List Of Values](jq/extract-a-list-of-values.md) diff --git a/jq/combine-an-array-of-objects-into-a-single-object.md b/jq/combine-an-array-of-objects-into-a-single-object.md new file mode 100644 index 0000000..bad18ff --- /dev/null +++ b/jq/combine-an-array-of-objects-into-a-single-object.md @@ -0,0 +1,40 @@ +# Combine An Array Of Objects Into A Single Object + +If you've spent any amount of time pulling data out of a JSON file with `jq`, +you may have run into a result set that looks a little too spacious. It's this +array of single key-value pair objects. + +```bash +$ jq '.items | map({(.slug)}: .amount})' my-data.json + +[ + { + "key-1": 123 + }, + { + "key-2": 345 + }, + { + "key-3": 456 + }, + ... +] +``` + +When what you really wanted was a single object full of those unique key-value +pairs. + +That query has you 90% of the way there. The trick is to pipe that array +through the [`add` function](https://jqlang.github.io/jq/manual/#add) which +will combine each of those individual objects into a single object. + +```bash +$ jq '.items | map({(.slug)}: .amount}) | add' my-data.json + +{ + "key-1": 123, + "key-2": 345, + "key-3": 456, + ... +} +```