假设我有一个对象,它是另一个对象的属性,我能找到父对象吗?
A[a] = o
我有o
,如何得到A
?进一步,如果A
是B
的属性,如何找到链?
最佳答案
你不能。考虑:
foo = {}
A.x = foo
B.y = foo
谁是 foo 的“父级”?
但是,如果所有“根”对象都是已知的,您可以通过递归遍历对象树来找到“父对象”:
scope = {}
foo = {"str": "hey"}
scope.A = { x: 1, y: { parent: foo }}
scope.B = { x: 5, zz: foo }
function findParent(what, where) {
if(typeof where !== "object")
return;
var found;
Object.keys(where).some(function(k) {
if(where[k] == what)
return found = where;
return found = findParent(what, where[k]);
})
return found;
}
par = findParent(foo, scope);
document.write(JSON.stringify(par));
可以扩展此代码以查找所有“ parent ”而不是第一个。
关于javascript - 如何知道对象的父链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31561160/