[英]Dynamic name in json key
我正在嘗試動態制作JSON,但是當我做這樣的事情時:
var jsonVar = {
"section": {}
}
var elementsStoragePrefix = "_app_",
elementName = elementsStoragePrefix + "some_name";
$.extend(jsonVar .section, { elementName: "<option>This is a text</option>"});
我得到的鍵是elementName而不是_app_some_name
jsonVar.section =>
Object
elementName: "<option>This is a text</option>"
__proto__: Object
在創建對象文字時,您不需要引用屬性名稱,因此在您的示例中, elementName
將按字面意思進行。 值得慶幸的是,你可以使用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);
那應該為你解決問題
jsonVar.section[elementName] = "<option>This is a text</option>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.