I have this JSON:
[{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }]
I would like to know if it is possible to change the name of 'total' to 'price' using JavaScript or jQuery?
I have this JSON:
[{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }]
I would like to know if it is possible to change the name of 'total' to 'price' using JavaScript or jQuery?
You can do this easily using the map()
.
let json = '[{ "id": 1, "total": 50.00 }, { "id": 2, "total": 70.00 }]';
let array = JSON.parse(json);
let novoArray = array.map(function(item){
return { id: item.id, preco: item.total };
});
console.log(novoArray);
You can also maintain the original property. This avoids having to copy all properties within the function.
let json = '[{ "id": 1, "total": 50.00 }, { "id": 2, "total": 70.00 }]';
let array = JSON.parse(json);
let novoArray = array.map(function(item){
item.preco = item.total;
return item;
});
console.log(novoArray);
Hello, I do not know if this would be the best way to do it, but you could turn it into a string, swap it, then turn it into JSON again. Something like this:
var json = [{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }];
var string = JSON.stringify(json);
string = string.replace(/\"total\":/g, "\"preco\":");
json = JSON.parse(string);
console.log(json);