I have a code like below
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
But seems like arrow function (=>) wont work in my environment and getting below error.
arrow function syntax (=>)' is only available in ES6 (use 'esversion: 6')
It is Apigee environment and I dont have permission to change any configuration. When I remove the arrow function and calling as a normal function like below, it is failing
const arr = JSON.parse(json);
arr.forEach(renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
So, for changing the each key in the JSON, how can I use the forEach loop or it would be helpful if there is an alternate method. Could anyone please suggest.
CodePudding user response:
If you like to use a closure with this
arr.forEach(renameKey('_id', 'id'))
pattern, you could take a closure over old and new key name and return a function which accepts the object for renaming.
function renameKey (oldKey, newKey) {
return function (obj) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
};
}
CodePudding user response:
const arr = JSON.parse(json);
arr.forEach(function(obj){ renameKey( obj, '_id', 'id' ) });
const updatedJson = JSON.stringify( arr );