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


当前回答

你还可以使用extend函数在json中添加新的json对象,

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

对于扩展函数,一个非常好的选择是递归合并。只需添加true值作为第一个参数(阅读文档了解更多选项)。的例子,

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}}

其他回答

你也可以使用Object。指定从ECMAScript 2015。它还允许您一次性添加嵌套属性。例如:

const myObject = {};

Object.assign(myObject, {
    firstNewAttribute: {
        nestedAttribute: 'woohoo!'
    }
});

Ps:这将不会覆盖现有的对象与分配的属性。相反,它们会被添加。但是,如果您将一个值赋给一个现有的属性,那么它将被覆盖。

JSON对象只是一个javascript对象,所以javascript是一种基于原型的语言,你所要做的就是使用点表示法来处理它。

mything.NewField = 'foo';
extend: function(){
    if(arguments.length === 0){ return; }
    var x = arguments.length === 1 ? this : arguments[0];
    var y;

    for(var i = 1, len = arguments.length; i < len; i++) {
        y = arguments[i];
        for(var key in y){
            if(!(y[key] instanceof Function)){
                x[key] = y[key];
            }
        }           
    };

    return x;
}

扩展多个json对象(忽略函数):

extend({obj: 'hej'}, {obj2: 'helo'}, {obj3: {objinside: 'yes'}});

会产生一个json对象吗

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);

您还可以直接在对象文字中动态地添加带有变量的属性。

const amountAttribute = 'amount';
const foo = {
                [amountAttribute]: 1
            };
foo[amountAttribute + "__more"] = 2;

结果:

{
    amount: 1, 
    amount__more: 2
}