CodeKaro CodeKaro - 3 months ago 9
jQuery Question

Remove all arrays that has power == 0

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!

Answer

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:

  1. Iterate over the JSON children.
  2. Check if the power is "0.00".
    • If it is, remove it (return null)
  3. Check if it has children
    • If it does, then iterate over it (go to step 2)
  4. Return the JSON element.
Comments