Kyle Hotchkiss
Kyle Hotchkiss

Reputation: 11112

Most efficent way to remove all children in a Javascript object, at any level, with a certain name?

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

Answers (2)

user663031
user663031

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

adeneo
adeneo

Reputation: 318312

Just iterate recursively and remove

function remove(obj, what) {
    (function stuff(o) {
        for (var key in o) 
            key && key == what ? delete o[key] : stuff(o[key]);
    })(obj);
}

FIDDLE

Upvotes: 3

Related Questions