title: Get the "path" of a JSON object in JavaScript
body: <p>I am trying to get the "path" of an AngularJS scope variable and not having much luck. I want to eventually pass that "path" to be used as the <code>ng-model</code> of some dynamic forms that are being created.</p>
  
  <p>Here is my code so far:</p>
  
  <p><strong>my_code.js:</strong></p>
  
  <pre><code>var my_data = {
    name: "fred",
    number: 1,
    children: [
      { name: "bob" },
      { name: "joe" },
      { name: "norman" },
    ]
  };
  
  function get_path(obj, target, path) {
  
    if (typeof path === "undefined" || path === null) { 
      path = "my_data";
    }
  
    for (var key in obj) {
      var value = obj[key];
      var value_type = value.constructor;
  
      /* value can either be an Array */
      if (value_type === Array) {
        for (var i=0; i&lt;value.length; i++) {
          if (value[i] === target) {
            return path + "." + key + "[" + i + "]";
          }        
          var result = get_path(value, target, path + "." + key + "[" + i + "]");  
          if (result) {
            return result;
          }
        }
      }
  
      /* or an Object (dictionary) itself */
      else if (value_type === Object) {
        var result = get_path(value, target, path + "." + key);
        if (result) {
          return result;
        }
      }
  
      /* or something atomic (string, number, etc.) */
      else {
        if (value === target) {
          return path + "." + key;
        }
      }  
    }
    return false;
  }
  </code></pre>
  
  <p>If I pass the <em>object</em> <code>my_data.children[0].name</code> to this function, I would expect it to return the <em>string</em> "my_data.children[0].name".  But it is actually returning "my_data.children[0].0.name".  Any ideas on where I'm going wrong?</p>
  
  <p>P.S. - I got the initial idea from <a href="https://stackoverflow.com/questions/8790607/javascript-json-get-path-to-given-subnode">Javascript/JSON get path to given subnode?</a>, but that didn't handle Arrays.</p>