trubliphone
trubliphone

Reputation: 4504

Get the "path" of a JSON object in JavaScript

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 ng-model of some dynamic forms that are being created.

Here is my code so far:

my_code.js:

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<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;
}

If I pass the object my_data.children[0].name to this function, I would expect it to return the string "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.S. - I got the initial idea from Javascript/JSON get path to given subnode?, but that didn't handle Arrays.

Upvotes: 2

Views: 1937

Answers (2)

trubliphone
trubliphone

Reputation: 4504

@min-hong-tan solved the problem, and should be the accepted answer. But for completeness sake, I added the following lines:

if (value === target) {
  return path + "." + key;
}

after each if block just in case I was trying to match an entire Array (as with my_data.children) or an entire Object that is not part of an Array.

Upvotes: 0

Min Hong Tan
Min Hong Tan

Reputation: 545

I think your error is at :

else if (value_type === Object) {

      var result = get_path(value, target, path + "." + key);
      if (result) {
        return result;
      }
    }

you have added "." + key. just remove it become like below:

else if (value_type === Object) {

      var result = get_path(value, target, path  );
      if (result) {
        return result;
      }
    }

Upvotes: 3

Related Questions