I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model
for dynamically generated forms.
Below is my current code:
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;
}
When I pass the object my_data.children[0].name
into this function, I anticipate receiving the string "my_data.children[0].name". However, it returns "my_data.children[0].0.name" instead. Can anyone pinpoint where I might be making a mistake?
P.S. - The initial inspiration for this solution came from Javascript/JSON get path to given subnode?, although it didn't account for Arrays.