最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic name in json key - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question edited Feb 3, 2013 at 0:21 mvp 116k15 gold badges129 silver badges153 bronze badges asked Feb 3, 2013 at 0:16 Sergio FloresSergio Flores 5,4275 gold badges38 silver badges60 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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

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

评论列表(0)

  1. 暂无评论