Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript deep remove object property by using another object as selector

Tags:

I have object like this:

var myObj = {
    first: {
        sub: {
            prop1: "some text",
            prop2: "some more text"
        },
        sub2: {
            prop1: "Something",
            prop2: "Something2",
        }
    },
    second: {
        stuff: "More stuff...lots of stuff"
    }
}

I'm trying to remove property from this object by using another object as selector. For example:

var delSeletor = {
    first: {
        sub: {
            prop2: ""
        }
    }
}

So delete( delSelector, myObject) should return:

var myObj = {
    first: {
        sub: {
            prop1: "some text",
        },
        sub2: {
            prop1: "Something",
            prop2: "Something2",
        }
    },
    second: {
        stuff: "More stuff...lots of stuff"
    }
}

Please note that I'm not looking for solution using the ".dot" selector eg: delete('first.sub.prop2', myObj) like shown in this thread.

like image 971
BlackHOST Avatar asked Jun 01 '17 11:06

BlackHOST


1 Answers

You could iterate the object selector for the keys to delete and check

  • if key does not exist, return
  • if property of the selector object is an object then call the delete function deleteKeys again with the key. Otherwise delete the key form the source object.

function deleteKeys(object, selector) {
    Object.keys(selector).forEach(function (k) {
        if(!(k in object)) {
            return;
        }
        if (typeof selector[k] === 'object') {
            deleteKeys(object[k], selector[k]);
        } else {
            delete object[k];
        }
    });
}

var myObj = { first: { sub: { prop1: "some text", prop2: "some more text" }, sub2: { prop1: "Something", prop2: "Something2", } }, second: { stuff: "More stuff...lots of stuff" } },
    delSeletor = { first: { sub: { prop2: "" } } };

deleteKeys(myObj, delSeletor);

console.log(myObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 118
Nina Scholz Avatar answered Sep 20 '22 14:09

Nina Scholz