Dynamic name in json key

I am trying to do JSON dynamically, but when I do something like this:

var jsonVar = {
    "section": {}
}

var elementsStoragePrefix = "_app_", 
    elementName = elementsStoragePrefix + "some_name";

$.extend(jsonVar .section, { elementName: "<option>This is a text</option>"});

I got the key as elementName, not _app_some_name

jsonVar.section =>
    Object
        elementName: "<option>This is a text</option>"
        __proto__: Object
+5
source share
2 answers

When creating object literals, you do not need to specify property names, so in your example it elementNamewill be taken literally. Fortunately, you can use the syntax with a square bracket (or, nevertheless, you say it):

var extendObject = {};
extendObject[elementName] = '<option>Foobar</option>';
$.extend(jsonVal.section, extendObject);
//or, to use brackets all the way:
$.extend(jsonVal['section'], extendObject);

That should fix things for you.

+9
source
jsonVar.section[elementName] = "<option>This is a text</option>";
+4
source

All Articles