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.
You could iterate the object selector
for the keys to delete and check
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With