title: JavaScript: how to filter deep JSON objects
body: <p>I have an array of deep JSON objects that look like similarly to this:</p>
  
  <pre><code>var hierarchy = [
    {
      "title": "category 1",
      "children": [
        {"title": "subcategory 1",
          "children": [
            {"id": 1, "title": "name 1"},
            {"id": 2, "title": "name 2"},
            {"id": 3, "title": "name 3"}
          ]
        },
        {"title": "subcategory 2",
          "children": [
            {"id": 1, "title": "name 4"}
          ]
        }
      ]
    },
    {
      "title": "category 2",
      "children": [etc. - shortened for brevity]
    }
  ];
  </code></pre>
  
  <p>So basically it is a hierarchy - there are categories which can have subcategories which contain objects with some IDs and names. I also have an array of IDs that are related to the deepest hierarchy level (objects with no children) and I need to filter this set of objects in such a way that only (sub)categories that contain defined objects remain.</p>
  
  <p>So for example if I had an array containing two IDs:</p>
  
  <pre><code>var IDs = [2, 3];
  </code></pre>
  
  <p>the result would be: </p>
  
  <pre><code>var hierarchy = [
    {
      "title": "category 1",
      "children": [
        {"title": "subcategory 1",
          "children": [
            {"id": 2, "title": "name 2"},
            {"id": 3, "title": "name 3"}
          ]
        }
      ]
    }
  ];
  </code></pre>
  
  <p>i.e. the whole, the whole 'category 2' object removed, the whole 'subcategory 2' removed, object with ID '1' removed.</p>
  
  <p>The problem is that the depth of those objects is variable and unknown - some objects have no children, some have children that also have children etc., any subcategory can can itself have a subcategory and I basically need to find object with no children that have defined IDs and keep the whole path to each of them.</p>
  
  <p>Thank you.</p>