Skip to content

Instantly share code, notes, and snippets.

@aurbano
Last active November 29, 2022 21:57
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save aurbano/383e691368780e7f5c98 to your computer and use it in GitHub Desktop.
Save aurbano/383e691368780e7f5c98 to your computer and use it in GitHub Desktop.
Remove a property from a nested object, recursively
/**
* Remove all specified keys from an object, no matter how deep they are.
* The removal is done in place, so run it on a copy if you don't want to modify the original object.
* This function has no limit so circular objects will probably crash the browser
*
* @param obj The object from where you want to remove the keys
* @param keys An array of property names (strings) to remove
*/
function removeKeys(obj, keys){
var index;
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
switch(typeof(obj[prop])){
case 'string':
index = keys.indexOf(prop);
if(index > -1){
delete obj[prop];
}
break;
case 'object':
index = keys.indexOf(prop);
if(index > -1){
delete obj[prop];
}else{
removeKeys(obj[prop], keys);
}
break;
}
}
}
}
@johnrails
Copy link

@mac2000 that's a nice solution except for every object you remove it is replaced with an empty object, so if i have an array of objects, and i want to remove one of them from the array it is replaced with an empty object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment