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


当前回答

以下工作为我添加了一个名为“id”的新字段。 Angular Slickgrid通常需要这样的id

  addId() {
     this.apiData.forEach((item, index) => {
     item.id = index+1;
  });

其他回答

你还可以使用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:这将不会覆盖现有的对象与分配的属性。相反,它们会被添加。但是,如果您将一个值赋给一个现有的属性,那么它将被覆盖。

以下工作为我添加了一个名为“id”的新字段。 Angular Slickgrid通常需要这样的id

  addId() {
     this.apiData.forEach((item, index) => {
     item.id = index+1;
  });

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

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

结果:

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