Reputation: 11112
Given an object like so, which won't always have the exact same structure,
data: {
deleteMe: true,
level1: {
level2: {
deleteMe: true,
level3: {
level4: {
level5: {
deleteMe: true
}
}
}
}
}
}
What is the most efficent way to loop though this entire object, in Javascript, that will allow me to delete all the properties named deleteMe
.
Upvotes: 0
Views: 68
Reputation:
Traverse the object recursively:
function remove_deleteMe(o) {
if (o && typeof o === 'object') {
delete o.deleteMe;
Object.keys(o).forEach(function(k) { remove_deleteMe(o[k]); });
}
}
Or, if you would prefer to specify the name of the property to be deleted:
function removeProp(o, propName) {
if (o && typeof o === 'object') {
delete o[propName];
Object.keys(o).forEach(function(k) { removeProp(o[k], propName); });
}
}
removeProp(data, 'deleteMe');
Actually @adeneo's approach is more compact and readable, taking advantage of the fact that for...in
works on non-objects. Taking some liberties:
function removeProp(o, propName) {
for (var k in o) {
if (k === propname) delete o[k];
removeProp(o[k], propName);
}
}
Upvotes: 1