Reputation:
I have JSON data and I want to update items on it.
How can I add a name
attribute to ALL id's in controller ?
{
"games" : [
{ "id":["1"] },
{ "id":["2"] },
{ "id":["3"] },
{ "id":["4"] },
{ "id":["5"] },
{ "id":["6"] }
]
}
Should be :
{
"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;
}
Upvotes: 1
Views: 103
Reputation: 7605
Use forEach
to loop through every items of the data.games
array and then simply add the name
property using 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);
Upvotes: 3