Search code examples
javascriptobject-literal

How to add to a multi object literal in Javascript?


Data sample taken from JQVmap:

var jvmCountries = {
  "AF": {"name": "Afghanistan", "coords": [33, 65]},
  "AL": {"name": "Albania", "coords": [41, 20]},
  "DZ": {"name": "Algeria", "coords": [28, 3]},
  "AO": {"name": "Angola", "coords": [-12.5, 18.5]},
  "AR": {"name": "Argentina", "coords": [-34, -64]},
  "AM": {"name": "Armenia", "coords": [40, 45]}
}

How can I add a new country to this? I believe you can add to an object literal using Object.assign(), but I'm not sure how to do so with those country abbreviation keys and each country having multiple values (a name and coords).


Solution

  • You might find Working with objects helpful in this case, but adding properties (in your case a country containing an object) can be done like this:

    jvmCountries['AA'] = {
      name: 'A New Country',
      coords: [500, 404]
    };