使用JavaScript将新属性(元素)添加到JSON对象

如何使用JavaScript将新属性(元素)添加到JSON对象?

ProA2020/03/16 11:42:07

You can also add new json objects into your json, using the extend function,

var newJson = $.extend({}, {my:"json"}, {other:"json"});
// result -> {my: "json", other: "json"}

A very good option for the extend function is the recursive merge. Just add the true value as the first parameter (read the documentation for more options). Example,

var newJson = $.extend(true, {}, {
    my:"json",
    nestedJson: {a1:1, a2:2}
}, {
    other:"json",
    nestedJson: {b1:1, b2:2}
});
// result -> {my: "json", other: "json", nestedJson: {a1:1, a2:2, b1:1, b2:2}}
神无Davaid2020/03/16 11:42:07
var jsonObj = {
    members: 
           {
            host: "hostName",
            viewers: 
            {
                user1: "value1",
                user2: "value2",
                user3: "value3"
            }
        }
}

var i;

for(i=4; i<=8; i++){
    var newUser = "user" + i;
    var newValue = "value" + i;
    jsonObj.members.viewers[newUser] = newValue ;

}

console.log(jsonObj);
阳光猿2020/03/16 11:42:06

JSON代表JavaScript Object Notation。JSON对象实际上是一个字符串,尚未转换为它表示的对象。

要将属性添加到JS中的现有对象,可以执行以下操作。

object["property"] = value;

要么

object.property = value;

如果您提供一些额外的信息,例如您在上下文中确实需要做的事情,那么您可能会得到一个更量身定制的答案。