7

I want to update my Object by adding a more key-value pair.

Object options = {
  "first_name": "Nitish",
  "last_name" : "Singh"
}

after initializing the Object I want to add one more key and value. Is there any way to do this.

after adding one more key-value pair my object will look like this

options = {
  "first_name" : "Nitish",
  "last_name"  : "Singh"
  "middle_name": "Kumar"
}
nitishk72
  • 1,616
  • 3
  • 12
  • 21

1 Answers1

7

You can assign to a Map using the indexing operator

options['middle_name'] = 'Kumar';

{} is a Map literal to create a Map instance. The result allows you to use all methods of Map like remove

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I got this error : The operator '[]=' isn't defined for the class 'Object' – nitishk72 May 09 '18 at 03:54
  • 1
    That's an analyzer warning. Use `var` or `final` instead of `Object` to have the type inferred or use `Map` or `Map` to specify a concrete type yourself. See also my updated answer. – Günter Zöchbauer May 09 '18 at 03:57
  • 1
    If you don't want to overwrite a value if the key already exists, then there is also `map.putIfAbsent(key, () => valueIfAbsent);` – Ganymede May 09 '18 at 16:41