Reputation: 1317
I have a complex JSON file with arrays and objects containing arrays and objects down about 10 levels. I load the JSON file into Node.js. I am trying to write a function that searches the entire object including all sub objects and sub arrays and deletes any key with a specific name. This is what I have:
function deleteKey(object, key) {
for(var property in object) {
if(property==key) {
delete object[property];
} else {
deleteKey(object[property], key);
}
}
}
I am getting a stack size exceeded error. Is there a better way?
Upvotes: 2
Views: 1250
Reputation: 116
Assuming as you would want this function to work on a JavaScript object of any depth, this would be a good situation to take advantage of recursion.
function deleteKey(object, key) {
for(var property in object) {
if(property==key) {
delete object[property];
} else {
if(object[property] !== null && typeof object[property] == 'object'){
deleteKey(object[property], key);
}
}
}
}
Upvotes: 3