title: Javascript get full index of nested object
body: <pre><code>const items = [
     { id: 'item1',
       children: [ 
        { id: 'item1-1',
          children: [
            { id: 'item1-1-1' },
            { id: 'item1-1-2' },
            { id: 'item1-1-3'
              children: [
                 { id: 'item1-1-3-1'}
              ]
            },
          ]
        },
        { id: 'item1-2',
          children: [
            { id: 'item1-2-1' }
          ]
        }
      ]
     },
     { id: 'item2' }
  ]
  </code></pre>
  
  <p>What I want to is like below, </p>
  
  <pre><code>function getFullDepthOfObject(){
    ...
  }
  
  getFullIndexOfObject('item1') =====&gt; return '1'
  getFullIndexOfObject('item1-2') =====&gt; return '1-2'
  getFullIndexOfObject('item1-1-1') =====&gt; return '1-1-1'
  getFullIndexOfObject('item1-1-2') =====&gt; return '1-1-2'
  getFullIndexOfObject('item2') ===&gt; return '2'
  </code></pre>
  
  <p>I have struggled with this too much time, But I couldn't make it. I think I should stack each of <code>parent</code> index, But I don't know how to get its parent. Is there a way to do this?</p>
  
  <p>Not parse of <code>id</code> string. Each id has randomic string. The id like <code>item1-2</code> is for easier demonstration. </p>
  
  <p>I think my way is too verbose...
  I tried like ...</p>
  
  <pre><code>// Get Full Index of item1-1
  
  
  // First, get the target's depth.
  var depth = 0;
  
  function getDepthOfId(object, id) {
      var level;
      if (object.id === id) return 1;
      object.children &amp;&amp; object.children.some(o =&gt; level = getDepthOfId(o, id));
      return level &amp;&amp; level + 1;
  }
  
  depth = getDepthOfId(items[0], 'item1-1');
  console.log('depth === ', depth)
  
  
  // Then, iterate recursively with length of depth.
  
  var indexStacks = [];
  
  
  function getNestedIndexOfId(obj, id, index) {
      if (obj.id === id) {
          indexStacks = [index, ...indexStacks]
          return index;
      }
  
      if (obj.children) {
          depth++;
          obj.children.map((child, i) =&gt; {
              getNestedIndexOfId(child, id, i)
          })
      }
  }
  
  // I can get the inner index, but I can't get its parent id.
  // I don't know how to this..
  
  function getParentId(obj, id){
      // ...?
      var parentId;
      return parentId;
  }
  
  for(var i=0; i&lt;depth; i++){
          getNestedIndexOfId('...')
  }
  
  
  // full path will be 
  indexStacks.join('-')
  </code></pre>