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

Asked

Viewed 1,019 times

1

I have this JSON:

[{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }]

I wonder if it is possible to change the name from 'total' to 'price' using Javascript or jQuery?

2 answers

6


You can do this easily using the function 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 keep the original property. This avoids having to copy all properties inside 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);

  • +1 @LINQ good solution

0

Hello, I don’t know if it would be the best way to do but you could turn into string, swap, then turn 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.