1

I'm creating a json to get interpreted for dialog creation.

My original attempt is something like this:

var dialog = {};
dialog.warning.nextEle["key"] = "value";

hoping that it would just generate the 'warning' and 'nextEle'. I could do something like this:

dialogMsg["warning"] = {"nextEle" : {"key" : "value"}};

but what I'm wanting is to be able to make it add to dialog.warning.nextEle if it already exists and add that depth if it doesn't already exist... ie:

{} would become

{ "warning" : { "nextEle" : { "key" : "value"}}}

and using the same format, I could add to make it

{ "warning" : { "nextEle" : { "key" : "value", "key2" : "value2"}}}

is it possible to do this without using conditionals?

Smern
  • 18,746
  • 21
  • 72
  • 90
  • What language are you using? – AlexLordThorsen Mar 19 '13 at 18:47
  • So I was thinking you could make a function which takes in a dictionary and a key. The function does dialog[key] = passed_dict. That way you could call it as many times as you want to nest your loop. Here's an SO answer I think may be useful to you. http://stackoverflow.com/questions/3559070/are-there-dictionaries-in-javascript-like-python – AlexLordThorsen Mar 19 '13 at 19:04
  • Sorry, I couldn't find what I'm looking for in that. – Smern Mar 19 '13 at 19:17

1 Answers1

2

If you are using jQuery, make use of the extend function, it will add the necessary components automatically.

$.extend(true, dialog,{ 
    "warning" : { 
        "nextEle" : { 
            "key" : "value"
        }
    }
});
Matt Dodge
  • 10,833
  • 7
  • 38
  • 58
  • hey matt, that actually seems to be overwriting existing content within warning/nextEle (rather than adding to it if it already exists): http://jsfiddle.net/pborreli/pJgyu/ – Smern Mar 19 '13 at 19:16
  • @smerny Ah you are right, I left off the `true` as the first parameter. That makes it extend recursively so it won't replace anymore. I added the link to the function's documentation too, it can be quite powerful – Matt Dodge Mar 19 '13 at 19:19