Given a nested object like:
var x = {
'name': 'a',
'testObj': {
'blah': 8,
'testObj2': { // delete this obj
'blah2': 9,
'blah3': 'c'
}
},
'level': 1,
'children': [{
'name': 'b',
'level': 2,
'children': [{ // delete this obj
'name': 'c',
'level': 3
}]}]
};
how does one go about deleting a nested object if it contains a property with a value (in my example, the string 'c') one specifies within a function? With the end result being like this:
var x = {
'name': 'a',
'testObj': {
'blah': 8,
},
'level': 1,
'children': [{
'name': 'b',
'level': 2,
'children': []}]
};
Here's my code thus far:
function recursiveIteration(obj, callback) {
var k;
if (obj instanceof Object) {
for (k in obj){
if (obj.hasOwnProperty(k)){
recursiveIteration( obj[k], callback );
}
}
} else {
callback(obj); // this is the non-object val
}
}
function deleteObjByValue(object, word) {
return recursiveIteration(object, function(val) {
if (word === val){
// here I want to delete the nested object (not the whole object) that contains the property with this val assigned to it
}else {
return false;
}
});
}
deleteObjByValue(x, 'c');