Better merge array by key example, fixed spelling mistakes

This commit is contained in:
Mike Farah 2021-11-29 20:56:49 +11:00
parent 61f561a9e0
commit fd3ee46ccf
3 changed files with 13 additions and 7 deletions

View File

@ -108,7 +108,7 @@ will output
a: frog
```
## Two non existant keys are equal
## Two non existent keys are equal
Given a sample.yml file of:
```yaml
a: frog

View File

@ -234,10 +234,12 @@ will output
```
## Merge arrays of objects together, matching on a key
It's a complex command, the trickyness comes from needing to have the right context in the expressions.
First we save the second array into a variable '$two' which lets us reference it later.
We then need to update the first array. We will use the relative update (|=) because we need to update relative to the current element of the array in the LHS in the RHS expression.
We set the current element of the first array as $cur. Now we multiply (merge) $cur with the matching entry in $two, by passing $two through a select filter.
There are two parts of the complex expression. The first part is doing the hard work, it creates a map from the arrays keyed by '.a',
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)
Given a sample.yml file of:
@ -260,7 +262,9 @@ And another sample another.yml file of:
```
then
```bash
yq eval-all '(select(fi==1) | .[]) as $two | select(fi==0) | .[] |= (. as $cur | $cur * ($two | select(.a == $cur.a)))' sample.yml another.yml
yq eval-all '((.[] | {.a: .}) as $item ireduce ({}; . * $item )) as $uniqueMap
| ( $uniqueMap | to_entries | .[]) as $item ireduce([]; . + $item.value)
' sample.yml another.yml
```
will output
```yaml
@ -271,6 +275,8 @@ will output
- a: banana
b: bananaB
c: bananaC
- a: dingo
c: dingoC
```
## Merge to prefix an element

View File

@ -209,7 +209,7 @@ will output
```
## Test using regex
Like jq'q equivalant, this works like match but only returns true/false instead of full match details
Like jq'q equivalent, this works like match but only returns true/false instead of full match details
Given a sample.yml file of:
```yaml