I have a JSON object with the following content:
[
{
\"_id\":\"5078c3a803ff4197dc81fbfb\",
\"email\":\"user1@gmail.com\",
\"image\":\"some_imag
JSON.parse has two parameters. The second parameter, reviver, is a transform function that can be formatted output format we want. See ECMA specification here.
In reviver function:
this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}]';
const obj = JSON.parse(json, function(k, v) {
if (k === "_id") {
this.id = v;
return; # if return undefined, orignal property will be removed
}
return v;
});
const res = JSON.stringify(obj);
console.log(res)
output:
[{"email":"user1@gmail.com","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"user2@gmail.com","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]