将新属性添加到JSON?

时间:2017-07-05 21:51:05

标签: javascript angularjs json

我有JSON数据,我想更新其中的项目。

如何在控制器中为所有ID添加name属性?

{ 
  "games" : [
      { "id":["1"] },
      { "id":["2"] },
      { "id":["3"] },
      { "id":["4"] },
      { "id":["5"] },
      { "id":["6"] }
   ]
}

应该是:

{ 
  "games" : [
      { "id":["1"],"name":"1" },
      { "id":["2"],"name":"2" },
      { "id":["3"],"name":"3" },
      { "id":["4"],"name":"4" },
      { "id":["5"],"name":"5" },
      { "id":["6"],"name":"6" }
   ]
}

for (var i = 1; i <= games.length; i++) {
    games[].name = i;
}

1 个答案:

答案 0 :(得分:4)

使用forEach循环浏览data.games数组的每个项目,然后使用name添加game.name = game.id[0]属性。

&#13;
&#13;
const data = { 
  "games" : [
      { "id":["1"] },
      { "id":["2"] },
      { "id":["3"] },
      { "id":["4"] },
      { "id":["5"] },
      { "id":["6"] }
   ]
};

data.games.forEach(game => game.name = game.id[0]);

console.log(data);
&#13;
&#13;
&#13;