title: How to traverse JSON object locating particular property and pushing its contents to array?
body: <p>I am working with a JSON object which can have a property <code>ids</code> at any leaf. I want to traverse the object and find all of the instances of the <code>ids</code> property and store each id in a collection.</p>
  
  <p>Mocked up JSON Object (the <code>ids</code> property could be at much deeper property locations).</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>{
    "id": "b38a683d-3fb6-408f-9ef6-f4b853ed1193",
    "foo": {
      "ids": [
        {
          "id": "bd0bf3bd-d6b9-4706-bfcb-9c867e47b881"
        },
        {
          "id": "d1cc529d-d5d2-4460-b2bb-acf24a7c5999"
        },
        {
          "id": "b68d0c8c-548e-472f-9b01-f25d4b199a71"
        }
      ],
      "baz": "super"
    },
    "bar": {
      "ids": [
        {
          "id": "bd0bf3bd-d6b9-4706-bfcb-9c867e47b881"
        },
        {
          "id": "d1cc529d-d5d2-4460-b2bb-acf24a7c5999"
        },
        {
          "id": "b68d0c8c-548e-472f-9b01-f25d4b199a71"
        }
      ]
    }
  }
  </code></pre>
  
  <p>I am using the following code to traverse the above JSON.</p>
  
  <pre class="lang-js prettyprint-override"><code>var jsonFile = require('./file_test.json'); // the above in my local directory
  
  function traverse(obj, ids) {
    for (var prop in obj) {
      if (typeof obj[prop] == "object" &amp;&amp; obj[prop]) {
        if (prop == 'ids') {
          for (var i = obj[prop].length - 1; i &gt;= 0; i--) {
            ids.push(obj[prop][i]._id);
          };
        }
        traverse(obj[prop], ids);
      }
    }
  }
  
  var ids = new Array();
  traverse(jsonFile, ids);
  
  console.log('ids', ids);
  </code></pre>
  
  <p>The above nets the following:</p>
  
  <pre class="lang-js prettyprint-override"><code>ids
  [
    'b68d0c8c-548e-472f-9b01-f25d4b199a71',
    'd1cc529d-d5d2-4460-b2bb-acf24a7c5999',
    'bd0bf3bd-d6b9-4706-bfcb-9c867e47b881',
    'b68d0c8c-548e-472f-9b01-f25d4b199a71',
    'd1cc529d-d5d2-4460-b2bb-acf24a7c5999',
    'bd0bf3bd-d6b9-4706-bfcb-9c867e47b881'
  ]
  </code></pre>
  
  <p>While my code works I am not convinced that I am doing this the most efficient or best way. Is there a better way to find all instances of the <code>ids</code> property? Perhaps without passing in an array but returning one? Or setting up for a callback with an <code>ids</code> array?</p>