oxy_js oxy_js - 6 months ago 28
Javascript Question

Recursively delete a list of values from object

I have a list of ids as

ids = [6,9]


and a object which is an array of objects as

data = {
"child": [{
"fruit": "apple",
"id": 1
},
{
"fruit": "mango",
"id": 2,
"child": [{
"name": "js",
"id": 4
}, {
"name": "jsk",
"id": 6
}]
},
{
"fruit": "banana",
"id": 9
}
]
}


I have to iterate over data to find any object with id present in list of ids.Here I have to delete

{"name":"jsk", "id": 6}


and

{"fruit":"banana","id":9}


To achieve this I have written following code

deleteObj = (data, ids) => {
data.child.forEach((key, index) => {
if(key && ids.indexOf(child.id) > -1){
console.log("inside match before", key);
key.splice(index, 1);
console.log("inside match after: ", key);
}
if(key.child) {
deleteObj(key, ids);
}
})
};


But in this function after getting first match it simply return.Deliting only first matched id.
Pring only
inside match after:9


Not able to find any error

Answer Source

You could use a simple while loop and iterate from the end, because splicing deletes the actual index and with moving on, you get an unprocessed item.

function deleteItems(array, ids) {
    var i = array.length;
    while (i--) {
        if (ids.indexOf(array[i].id) !== -1) {
            array.splice(i, 1);
            continue;
        }
        array[i].child && deleteItems(array[i].child, ids);
    }
}

var ids = [6, 9],
    data = { child: [{ fruit: "apple", id: 1 }, { fruit: "mango", id: 2, child: [{ name: "js", id: 4 }, { name: "jsk", id: 6 }] }, { fruit: "banana", id: 9 }] };

deleteItems([data], ids)
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download