Updating every property of a map (object), explained #2233
amn
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
If you have a map of nested maps, because I have recently struggled myself with a query, I'd like to show you how you can update each of the nested maps in a consistent fashion, using multiple approaches. Your input, a single map, may resemble the following:
Say you want to add one or several properties to each of the maps (keyed
apple
,potato
andacorn
), the shortest expression is probably something like:Approach 1
With the above, the map expressed with
{ "planet": "Earth", "season": "fall" }
is merged with every nested map (bound to.
insidewith_entries
):Approach 1.1
There's at least one variation on the above that produces equivalent result:
Approach 1.2
The above, can be further shortened to:
The way I understand it,
with_entries
is implemented in a manner where it's equivalent to:Approach 2
Remember the importance of operator precedence rules, assuming you only wanted to add one of the properties,
planet
, the below snippet will not yield the expected result:On the other hand, the following amendment on the above does work:
I hope all this is useful to someone.
Beta Was this translation helpful? Give feedback.
All reactions