I have a JSON data structure that is quite complex, like the one shown below:
const json = '{"desc":"zzz", "details": { "id": 1, "name": "abc", "categoryDetails": { "cid": 1, "name": "abc" } }}'
The task at hand is to write code that can dynamically rename keys within this JSON structure. Here's what I have attempted so far:
const obj = JSON.parse(json);
var renameKeys = [
{
oldKey: 'desc',
newKey: 'newdesc'
},
{
oldKey: 'details.name',
newKey: 'details.newname'
},
{
oldKey: 'details.categoryDetails.name',
newKey: 'details.categoryDetails.newname',
}
];
for (var i in renameKeys) {
var item = renameKeys[i];
if(obj[item.oldKey]) { //this throws error - undefined. It is possible that this key does not exist in some objects
obj[item.newKey] = obj[item.oldKey];
delete obj[item.oldKey];
}
}
Unfortunately, running this code snippet results in undefined errors (TypeError: Cannot read properties of undefined) with the for loop.
Despite the complexity of the JSON paths, we need to persist with this approach of defining old and new keys in order to correct hundreds of JSON documents.
How can we modify the renameKeys
array and the for loop
to ensure that this logic works correctly?