Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic name in json key

I'm trying to make a 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 and not _app_some_name

jsonVar.section =>
    Object
        elementName: "<option>This is a text</option>"
        __proto__: Object
like image 585
Sergio Flores Avatar asked Feb 03 '13 00:02

Sergio Flores


2 Answers

When creating object literals, you don't need to quote the property names, so in your example elementName will be taken literally. Thankfully, you can use the square-bracket-syntax (or however you spell that):

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

like image 75
Elias Van Ootegem Avatar answered Oct 13 '22 23:10

Elias Van Ootegem


jsonVar.section[elementName] = "<option>This is a text</option>";
like image 25
dimusic Avatar answered Oct 13 '22 21:10

dimusic