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


当前回答

从2015年开始使用ECMAScript,你可以使用扩展语法(…三个点):

let  people = { id: 4 ,firstName: 'John'};
people = { ...people, secondName: 'Fogerty'};

它允许你添加子对象:

people = { ...people, city: { state: 'California' }};

结果将是:

{  
   "id": 4,
   "firstName": "John",
   "secondName": "Forget",
   "city": {  
      "state": "California"
   }
}

你也可以合并对象:

var mergedObj = { ...obj1, ...obj2 };

其他回答

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

const myObject = {};

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

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

使用jquery的$.extend(),如下所示:

token = {_token:window.Laravel.csrfToken};
data = {v1:'asdass',v2:'sdfsdf'}
dat = $.extend(token,data); 

我希望你为他们服务。

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

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

结果:

{
    amount: 1, 
    amount__more: 2
}
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);