jj2
jj2

Reputation: 956

Adding key/values pairs to JSON map down one level

I'm trying to dynamically add new key/value pairs to an existing json map using jquery/javascript. An example of my structure is as follows:

var widgetTypes = {
  "CLASS_A": {
    "A1": "A1 Description",
    "A2": "A2 Description"
  },
  "CLASS_B": {
    "B1": "B1 Description",
    "B2": "B2 Description"
  }
};

How do I append a key/value pair to either class (i.e. CLASS_A or CLASS_B). For example, how would I add item A3 with description "A3 Description" to the CLASS_A section of the structure so that I then had the following?

var widgetTypes = {
  "CLASS_A": {
    "A1": "A1 Description",
    "A2": "A2 Description"
    "A3": "A3 Description"
  },
  "CLASS_B": {
    "B1": "B1 Description",
    "B2": "B2 Description"
  }
};

I know you can do something like widgetTypes['CLASS_A'].type = 'A3' etc. but I can't seem to get it quite right (or I'm way off the track). I found a lot of examples of adding items the level above (i.e. adding a CLASS_C) but nothing for what I'm interested in doing.

Upvotes: 2

Views: 88

Answers (2)

Jai
Jai

Reputation: 74738

There are several ways:

  1. . Dot notation.
  2. [] Bracket notation.
  3. Object.defineProperty() method.

var widgetTypes = {
  "CLASS_A": {
    "A1": "A1 Description",
    "A2": "A2 Description"
  },
  "CLASS_B": {
    "B1": "B1 Description",
    "B2": "B2 Description"
  }
};

1.

widgetTypes.CLASS_A.A3 = "A3 Description"

2.

widgetTypes["CLASS_A"]["A3"] = "A3 Description"

3.

Object.defineProperty(widgetTypes.CLASS_A, 'A3', {
  value: "A3 Description",
  writable: true,
  enumerable: true,
  configurable: true
});

Option 3 has several other advantages over the two that you can configure the property behavior.

Upvotes: 3

Amadan
Amadan

Reputation: 198304

widgetTypes.CLASS_A.A3 = "A3 Description";

or equivalently

widgetTypes["CLASS_A"]["A3"] = "A3 Description";

Upvotes: 3

Related Questions