I have a use case where there comes a JSON response from backend in the form as follows:
[
{
"name": "cab",
"child": [
{
"name": "def",
"child": [
{
"name": "ghi",
"power": "0.00",
"isParent": false
}
],
"power": "1.23",
"isParent": true
}
],
"power": "1.1",
"isParent": true
},
{
"name": "hhi",
"child": [
{
"name": "hhi2",
"child": [
{
"name": "hhi3",
"power": "0.00",
"isParent": false
}
],
"power": "1.23",
"isParent": true
}
],
"power": "1.1",
"isParent": true
}
]
I need to remove all objects that has power == 0. It's easy to use filter on simple collection of arrays, but there might be cases where any n number of childs can contain n number of childs in it.
Thanks in advance!
You can iterate recursively using Array#filter
with a named function expression:
var objArray = [{"name":"cab","child":[{"name":"def","child":[{"name":"ghi","power":"0.00","isParent":false}],"power":"1.23","isParent":true}],"power":"1.1","isParent":true},{"name":"hhi","child":[{"name":"hhi2","child":[{"name":"hhi3","power":"0.00","isParent":false}],"power":"1.23","isParent":true}],"power":"1.1","isParent":true}];
objArray = _.filter(objArray, function powerFilter(o) {
if (o.power == 0) return false;
if (o.isParent && o.child) {
o.child = _.filter(o.child, powerFilter); // recursive call
o.isParent = o.child.length > 0;
if (!o.isParent) delete o.child;
}
return true;
});
console.log(objArray);
<script src="https://cdn.jsdelivr.net/underscorejs/1.8.3/underscore-min.js"></script>
Just iterate over the arrays with a recursive function:
var json = ["JSON_HERE"];
function deleteIterator(json) {
if(json.power == "0.00") {
return null;
} else if(json.child) {
json.child = deleteIterator(json.child);
}
return json;
}
for(var i = 0; i < json.length; i++) {
json[i] = deleteIterator(json[i]);
}
What this does is:
"0.00"
.
null
)Recursively iterate through the object, looking for child each time and filter on power === 0 or whatever your requirements are.
If you dont know how to use recursion, here is a tutorial to get you started. I really hope someone doesnt come along after me and hand you the exact solution to your problem because this is something you should be able to solve yourself once you know how to use recursion. You could also use loops but.. recursion is best.
Edit: This problem has been solved before, in a different flavor, but all the same. If you find your implementation ends up having bugs you cant figure out, please feel free to mention me in a new question and i'll try my best to help you.
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