How to add key value-pair to a Object?

10,155

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

Share:
10,155
nitishk72
Author by

nitishk72

A developer who loves to work with various technology. Always ready to learn and explore new technologies. Expertise Primary: JavaScript. Secondary: Flutter Social My Website Youtube Channel GitHub Twitter

Updated on June 07, 2022

Comments

  • nitishk72
    nitishk72 about 2 years

    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
    nitishk72 about 6 years
    I got this error : The operator '[]=' isn't defined for the class 'Object'
  • Günter Zöchbauer
    Günter Zöchbauer about 6 years
    That's an analyzer warning. Use var or final instead of Object to have the type inferred or use Map or Map<String,String> to specify a concrete type yourself. See also my updated answer.
  • Ganymede
    Ganymede about 6 years
    If you don't want to overwrite a value if the key already exists, then there is also map.putIfAbsent(key, () => valueIfAbsent);