0

In groovy, I want to update (left merge) a map with another.

def item = [attributes:[color:'Blue', weight:500], name:'hat', price:150]
def itemUpdate = [attributes:[size: 10]]
item << itemUpdate
println item

Gives:

[attributes:[size:10], name:hat, price:150]

But what I want is:

[attributes:[color:'Blue', weight:500, size:10], name:'hat', price:150]

I have also tried:

item += itemUpdate

or using Updating groovy object fields from a map. None fulfils my requirements; in python the method would be the update() method.

Edit: I'm wrong about python actually.

Hugues Fontenelle
  • 5,275
  • 2
  • 29
  • 44

1 Answers1

1

What you're doing is effectively overwriting the attributes entry.

What you want to do, instead, is:

item.attributes = item.attributes + itemUpdate

You can even do:

item.attributes += itemUpdate

Both of which yield the expected

[attributes:[color:Blue, weight:500, size:10], name:hat, price:150]
ernest_k
  • 44,416
  • 5
  • 53
  • 99