获取“路径"JavaScript中的JSON对象 [英] Get the "path" of a JSON object in JavaScript
问题描述
我试图获取AngularJS作用域变量的路径",但运气不佳.我最终希望传递该路径",以用作正在创建的某些动态表单的 ng-model
.
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;
}
如果我将 object my_data.children [0] .name
传递给此函数,则希望它返回 string "my_data.children [0] .name".但实际上它返回的是"my_data.children [0] .0.name".关于我要去哪儿有什么想法吗?
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.-我从> JavaScript/JSON获取到给定子节点的路径获得了最初的想法?,但是不能处理数组.
P.S. - I got the initial idea from Javascript/JSON get path to given subnode?, but that didn't handle Arrays.
推荐答案
我认为您的错误在于:
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;
}
}
这篇关于获取“路径"JavaScript中的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!