From 418bd1a8067fd3319499355261f16fa2fa930706 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Mon, 29 Nov 2021 20:56:04 +1100 Subject: [PATCH] Added credit for merge by array example --- merge-array-by-key.sh | 8 ++++++++ pkg/yqlib/doc/multiply-merge.md | 2 ++ pkg/yqlib/operator_multiply_test.go | 2 ++ 3 files changed, 12 insertions(+) create mode 100755 merge-array-by-key.sh diff --git a/merge-array-by-key.sh b/merge-array-by-key.sh new file mode 100755 index 00000000..09481e62 --- /dev/null +++ b/merge-array-by-key.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# ./yq ea '.[]' examples/data*.yaml + + +./yq ea ' + ((.[] | {.name: .}) as $item ireduce ({}; . * $item )) as $uniqueMap + | ( $uniqueMap | to_entries | .[]) as $item ireduce([]; . + $item.value) +' examples/data*.yaml \ No newline at end of file diff --git a/pkg/yqlib/doc/multiply-merge.md b/pkg/yqlib/doc/multiply-merge.md index 000c8536..5e576b13 100644 --- a/pkg/yqlib/doc/multiply-merge.md +++ b/pkg/yqlib/doc/multiply-merge.md @@ -239,6 +239,8 @@ so that there are no duplicates. The second half converts that map back to an ar To use this, you will need to update '.[]' to be the expression to your array (e.g. .my.array[]), and '.a' to be the key field of your array (e.g. '.name') +Thanks Kev from [stackoverflow](https://stackoverflow.com/a/70109529/1168223) + Given a sample.yml file of: ```yaml diff --git a/pkg/yqlib/operator_multiply_test.go b/pkg/yqlib/operator_multiply_test.go index d95a6152..cff562e8 100644 --- a/pkg/yqlib/operator_multiply_test.go +++ b/pkg/yqlib/operator_multiply_test.go @@ -33,6 +33,8 @@ var mergeArraysObjectKeysText = `There are two parts of the complex expression. so that there are no duplicates. The second half converts that map back to an array. To use this, you will need to update '.[]' to be the expression to your array (e.g. .my.array[]), and '.a' to be the key field of your array (e.g. '.name') + +Thanks Kev from [stackoverflow](https://stackoverflow.com/a/70109529/1168223) ` var mergeExpression = `((.[] | {.a: .}) as $item ireduce ({}; . * $item )) as $uniqueMap