Smern
Smern

Reputation: 19066

Add multiple levels deep JSON easily

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?

Upvotes: 1

Views: 215

Answers (1)

Matt Dodge
Matt Dodge

Reputation: 11142

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"
        }
    }
});

Upvotes: 2

Related Questions