David Richied David Richied - 2 months ago 8x
Javascript Question

How to remove a child object in a multidimensional JavaScript object?

I've come to the conclusion that this is near impossible. In the picture below, I am trying to remove the object with the key of 36 without knowing the key of its parent(s).
Picture of My Multidimensional JavaScript Object

I was able to find the object with the key of 36 using the the following function (where o is the object and id is the key), but, then, there's no way I can see to remove the child object from the object.

function findById(o, id) {
//Early return
if( o.id === id ){
return o;
var result, p;
for (p in o) {
if( o.hasOwnProperty(p) && typeof o[p] === 'object' ) {
result = findById(o[p], id);
return result;
return result;

Before looking for another solution, I figured I may as well ask the experts of the SO programming community.

The solution's actually pretty simple (see answer below). I didn't realize o[p] in the first level of the recursion was a reference to the actual object, meaning that
delete o[p]
deletes it from the actual object.


If you can find it, you can find its parent. If you can find its parent, you can delete the key you're looking for. You can modify your function to do just that. It will return true on success.

function deleteId(o, id) {
    if(o.hasOwnProperty(id)) {
        return delete o[id];
    var p;
    for(p in o) {
        if(o.hasOwnProperty(p) && typeof o[p] === 'object') {
            var success = deleteId(o[p], id);
            if(success) {
                return true;
    return false;