使用Jquery在Click事件上将新属性附加到现有JSON对象

Rob*_*Rob 0 javascript jquery json object

我试图将输入字段中的值附加到existsng JSON对象中,并且我不断收到错误.

这是我的代码:

$('#addObjectBtn').click(function() {
            //Inject Property into current object
            var newObjName = $('#newObjectName').val();
            var newObjType = $('#newObjectType').val();
            objStr.View[newObjType + "_100"] = {"BackgroundImage":'""' + newObjName + '""'};
            $('#newObjectPrompt').dialog('close');
        })
Run Code Online (Sandbox Code Playgroud)

编辑:添加JSON对象.我试图添加例如另一个按钮.在我的例子中,这将是"Button_100"

{
    "View": {
        "Name": "Untitled3",
        "ImportWidth": 320,
        "ImportHeight": 480,
        "Image_1": {
            "BackgroundImage": "Image.png",
            "Position": [0, 0],
            "Width": 320,
            "Height": 480
        },
        "Button_1": {
            "BackgroundImage": "ButtonTop.png",
            "Position": [61, 83],
            "Width": 217,
            "Height": 58
        },
        "Button_2": {
            "BackgroundImage": "ButtonBottom.png",
            "Position": [81, 114],
            "Width": 205,
            "Height": 73
        },
        "TextField_1": {
            "BackgroundImage": "TextFieldLogin.png",
            "Position": [102, 336],
            "Width": 189,
            "Height": 31
        },
        "Label_1": {
            "Position": [137, 100],
            "Width": 54,
            "Height": 20,
            "Text": "HiRob",
            "FontSize": 18,
            "Color": [0, 0, 0, 1]
        },
        "Label_2": {
            "Position": [43, 342],
            "Width": 72,
            "Height": 20,
            "Text": "LogOut:",
            "FontSize": 18,
            "Color": [0, 0, 0, 1]
        },
        "Label_3": {
            "Position": [115, 234],
            "Width": 126,
            "Height": 20,
            "Text": "AnotherButton",
            "FontSize": 18,
            "Color": [0, 0, 0, 1]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

newObjType已经是一个字符串,你不需要所有这些引号.试试这样:

objStr.View[newObjName + "_100"] = {BackgroundImage: newObjType};
Run Code Online (Sandbox Code Playgroud)