I have a JSON object with the following content:
[
{
\"_id\":\"5078c3a803ff4197dc81fbfb\",
\"email\":\"user1@gmail.com\",
\"image\":\"some_imag
Try this:
let jsonArr = [
{
"_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"
}
]
let idModified = jsonArr.map(
obj => {
return {
"id" : obj._id,
"email":obj.email,
"image":obj.image,
"name":obj.name
}
}
);
console.log(idModified);
If you want to rename all occurrences of some key you can use a regex with the g option. For example:
var json = [{"_id":"1","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"user2@gmail.com","image":"some_image_url","name":"Name 2"}];
str = JSON.stringify(json);
now we have the json in string format in str.
Replace all occurrences of "_id" to "id" using regex with the g option:
str = str.replace(/\"_id\":/g, "\"id\":");
and return to json format:
json = JSON.parse(str);
now we have our json with the wanted key name.
const arr = JSON.parse(json);
obj.id = obj._id;
delete obj._id;
All together:
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
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 arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
console.log( updatedJson );
Is possible, using typeScript
function renameJson(json,oldkey,newkey) {
return Object.keys(json).reduce((s,item) =>
item == oldkey ? ({...s,[newkey]:json[oldkey]}) : ({...s,[item]:json[item]}),{})
}
Example: https://codepen.io/lelogualda/pen/BeNwWJ
In this case it would be easiest to use string replace. Serializing the JSON won't work well because _id will become the property name of the object and changing a property name is no simple task (at least not in most langauges, it's not so bad in javascript). Instead just do;
jsonString = jsonString.replace("\"_id\":", "\"id\":");