title: How do I recursively use Array.prototype.find() while returning a single object?
body: <p>The bigger problem I am trying to solve is, given this data:</p>
  <pre><code>var data = [
      { id: 1 },
      { id: 2 },
      { id: 3 },
      { id: 4, children: [
          { id: 6 },
          { id: 7, children: [
              {id: 8 },
              {id: 9 }
          ]}
      ]},
      { id: 5 }
  ]
  </code></pre>
  <p>I want to make a function <code>findById(data, id)</code> that returns <code>{ id: id }</code>. For example, <code>findById(data, 8)</code> should return <code>{ id: 8 }</code>, and <code>findById(data, 4)</code> should return <code>{ id: 4, children: [...] }</code>.</p>
  <p>To implement this, I used <code>Array.prototype.find</code> recursively, but ran into trouble when the <code>return</code> keeps mashing the objects together. My implementation returns the <em>path</em> to the specific object.</p>
  <p>For example, when I used <code>findById(data, 8)</code>, it returns the <em>path</em> to <code>{ id: 8 }</code>:</p>
  <pre><code> { id: 4, children: [ { id: 6 }, { id: 7, children: [ { id: 8}, { id: 9] } ] }
  </code></pre>
  <p>Instead I would like it to simply return</p>
  <pre><code>{ id: 8 }
  </code></pre>
  <hr />
  <h3>Implementation (Node.js v4.0.0)</h3>
  <p><a href="https://jsfiddle.net/q2k5vpqn/" rel="noreferrer">jsfiddle</a></p>
  <pre><code>var data = [
      { id: 1 },
      { id: 2 },
      { id: 3 },
      { id: 4, children: [
          { id: 6 },
          { id: 7, children: [
              {id: 8 },
              {id: 9 }
          ]}
      ]},
      { id: 5 }
  ]
  
  function findById(arr, id) {
      return arr.find(a =&gt; {
          if (a.children &amp;&amp; a.children.length &gt; 0) {
              return a.id === id ? true : findById(a.children, id)
          } else {
              return a.id === id
          }
      })
      return a
  }
  
  console.log(findById(data, 8)) // Should return { id: 8 }
  
  // Instead it returns the &quot;path&quot; block: (to reach 8, you go 4-&gt;7-&gt;8)
  //
  // { id: 4,
  //   children: [ { id: 6 }, { id: 7, children: [ {id: 8}, {id: 9] } ] }
  </code></pre>