如何将数据添加到json对象中?

时间:2014-08-21 07:42:49

标签: javascript jquery json

我正在尝试使用for循环将数据添加到json对象中,但push方法无效,因为它将对象添加到json数组中,是否有想法将数据添加到json对象中?

我的代码:

    var data = [
        { Name: "Jake", Gender: "Male", Address: "Address1" },
        { Name: "Laura", Gender: "Female", Address: "Address2" },
    ];

    for (var i = 0; i < data.length; i++) {
        if (data[i].Gender == "Male") {
            data[i].push({ Icon: "image/male.png" });
        } else {
            data[i].push({ Icon: "image/female.png" });
        }
    }

    var result = data;

我需要结果为:

result = [
            { Name: "Jake", Gender: "Male", Address: "Address1", Icon: "image/male.png" },
            { Name: "Laura", Gender: "Female", Address: "Address2", Icon: "image/female.png" },
        ];

将根据if条件

在每个对象中添加数据Icon

2 个答案:

答案 0 :(得分:4)

只有一个Icon,因此您可以直接设置它:

for (var i = 0; i < data.length; i++) {
    if (data[i].Gender == "Male") {
        data[i].Icon = "image/male.png";
    } else {
        data[i].Icon = "image/female.png";
    }
}

之前,您应该在控制台中看到错误,因为data[i]是一个对象(不是数组)并且没有任何方法push

答案 1 :(得分:0)

以下是您需要做的事情:

var data = [
        { Name: "Jake", Gender: "Male", Address: "Address1" },
        { Name: "Laura", Gender: "Female", Address: "Address2" },
    ];
    for (var i = 0; i < data.length; i++) {
        if (data[i].Gender == "Male") {
            data[i].Icon = "image/male.png";

        } else {
            data[i].Icon = "image/female.png";
        }
    }

    var result = data;
    alert(result[0].Icon);
    alert(result[1].Icon);

请参阅您的工作小提琴here