I need to rename the object key name dynamically in a nested array of object JavaScript, I had tried with this code. This also I got from Stack Overflow only but this is not working that means it checking first level only not doing deep replacing.
const node = {
'id': 'de603a3e',
'name': 'erewr',
'subGroups': [
{
'id': '83d7c7e4',
'name': 'dfds',
'subGroups': [ ]
},
{
'id': '050cde96',
'name': 'tetwet',
'subGroups': [ ]
},
{
'id': 'd67cc4e8',
'name': 'wewqe',
'subGroups': [
{
'id': '553c301d',
'name': 'ewqe',
'subGroups': [
]
}
]
},
{
'id': '5d5ae5f2',
'name': 'rwq',
'subGroups': [
{
'id': 'ff29ad54',
'name': 'wqe',
'subGroups': [
]
},
{
'id': '5d013943',
'name': 'weqe',
'subGroups': [
]
}
]
}
]
}
console.log(renameKey(node, { subGroups: 'subordinates' }))
renameKey(obj, keysMap) {
return transform(obj, function(result, value, key) {
const currentKey = keysMap[key] || key;
result[currentKey] = isObject(value) ? this.renameKey(value, keysMap) : value;
});
}
I am using this code in TypeScript.
note : transform and isObject are lodash
I am getting error ERROR TypeError: Cannot read property 'replaceKeysDeep' of undefined