我有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;
}
答案 0 :(得分:4)
使用forEach
循环浏览data.games
数组的每个项目,然后使用name
添加game.name = game.id[0]
属性。
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;