Associative array/Merging

From Rosetta Code
Revision as of 23:54, 13 January 2020 by JoeStrout (talk | contribs) (Created page with "{{draft task}} ;Task: Define two associative arrays, where one represents the following "base" data: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "name" || "Rocke...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Associative array/Merging is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Define two associative arrays, where one represents the following "base" data:

Key Value
"name" "Rocket Skates"
"price" 12.75
"color" "yellow"

And the other represents "update" data:

Key Value
"price" 15.25
"color" "red"
"year" 1974

Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:

Key Value
"name" "Rocket Skates"
"price" 15.25
"color" "red"
"year" 1974


MiniScript

MiniScript supports merging maps with the `+` operator. <lang MiniScript>base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974}

result = base + update

print result</lang>

Output:
{"color": "red", "name": "Rocket Skates", "price": 15.25, "year": 1974}