views:

62

answers:

3

I'm building the JSON object using JavaScript. How would I inset the following data to the bottom of the stack:

"hello": { "label":"Hello", "url":"#hello" }

in to the following variable:

var ListData = {
  "main": {
    "label":"Main",
    "url":"#main"
  },
  "project": {
    "label":"Project",
    "url":"#project"
  },
  "settings": {
    "label":"Settings",
    "url":"#settings",
    "subnav":[
      {
        "label":"Privacy",
        "url":"#privacy"
      },
      {
        "label":"Security",
        "url":"#security"
      },
      {
        "label":"Advanced",
        "url":"#advanced"
      }
    ]
  }
};

So the variable looks like:

var ListData = {
  "main": {
    "label":"Main",
    "url":"#main"
  },
  "project": {
    "label":"Project",
    "url":"#project"
  },
  "settings": {
    "label":"Settings",
    "url":"#settings",
    "subnav":[
      {
        "label":"Privacy",
        "url":"#privacy"
      },
      {
        "label":"Security",
        "url":"#security"
      },
      {
        "label":"Advanced",
        "url":"#advanced"
      }
    ]
  },
  "hello": {
    "label":"Hello",
    "url":"#hello"
  }
};

I used the following code but it doesn't seem to work:

var NewData = '"hello": { "label":"Hello", "url":"#hello" }';
ListData.push(NewData);
A: 

Keeping with you object literal statements just add another object to your ListData object.

ListData.hello = { "label":"Hello", "url":"#hello" };

push is only for Javascript Arrays.

Bobby Borszich
it will make too many hello's :)
Eldar Djafarov
@Eldar, whoops, corrected and thanks
Bobby Borszich
+2  A: 

You can insert it directly with an object literal:

ListData.hello = { label: "Hello", url: "#hello" }; 
Clay Hinson
Thanks, that worked. :-)
Tony2K
+1  A: 

If you are using jQuery, you can use the .extend() method like so:

$.extend(ListData, {"hello": { "label":"Hello", "url":"#hello" }});
Alex
This worked also.
Tony2K