Is it possible to change the name of a JSON position using JavaScript or jQuery?

1

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?

    
asked by anonymous 16.11.2017 / 16:28

2 answers

6

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);
    
16.11.2017 / 16:33
0

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);
    
16.11.2017 / 16:33