2

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.

2 Answers 2

3

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;
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

@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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.