How to merge objects in a collection with the same key #281
Replies: 2 comments 3 replies
-
Hi Jonathan! I'm a bit rusty, so there are likely more elegant solutions, but this should do the trick: package play
merged[x] { # 4. putting all objects in a set
input[_][key] # 1. enumerating the unique keys
set := {v | v := input[_][key][_]} # 2. joining all list items with the same key into a set
x := {key: set} # 3. making an object out of the key and associated set
} |
Beta Was this translation helpful? Give feedback.
-
For simple merges you have the object.union and object.union_n built-in functions to work with. There was a recent proposal by @charlesdaniels to add another one with object.union_merge, but as your requirements show, there aren't really any agreed-upon resolutions for merging values like arrays... so we'd either need to have one built-in per option, or provide some generic way of bringing in your own "conflict resolver".. which would be a challenge in a non-functional language like Rego, I think. So for the time being, you're probably best off with a custom implemnentation like the one @johanfylling provided here. |
Beta Was this translation helpful? Give feedback.
-
Hi I was looking at the object comprehension in order to decompose objects and transform them but am not getting a correct result.
Given my data
How would I transform it into just
I tried with a more complex dataset and query here https://play.openpolicyagent.org/p/Pw6kSPNU4R. Not sure why it doesn't merge together when the keys are the same as well
Beta Was this translation helpful? Give feedback.
All reactions