简体   繁体   English

json键中的动态名称

[英]Dynamic name in json key

I'm trying to make a JSON dynamically but when I do something like this: 我正在尝试动态制作JSON,但是当我做这样的事情时:

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 我得到的键是elementName而不是_app_some_name

jsonVar.section =>
    Object
        elementName: "<option>This is a text</option>"
        __proto__: Object

When creating object literals, you don't need to quote the property names, so in your example elementName will be taken literally. 在创建对象文字时,您不需要引用属性名称,因此在您的示例中, elementName将按字面意思进行。 Thankfully, you can use the square-bracket-syntax (or however you spell that): 值得庆幸的是,你可以使用square-bracket-syntax(或者你拼写):

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 那应该为你解决问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM