Reputation: 759
How could I generate a string of an object's path? For example, say I want to turn the following path (not its contents) into a string:
object = grandparent.children[2].children[4].whatever;
I need a function like this:
function stringifyPath(obj) {
// somehow return "grandparent.children[2].children[4].whatever";
}
Upvotes: 0
Views: 1216
Reputation: 707496
You simply can't do that in Javascript unless each object stores a reference to it's own parent and there's a known way to navigate children (like DOM nodes do).
This is because when you have an object embedded in another object (your parent/child relationship you speak of), it isn't really an object embedded in another. The child is an independent object and there's a reference to it in the parent. That same child could be stored in many different places. From Javascript's point of view, it doesn't actually have a parent. It's an object that many different things may have a reference to.
If each child object stored a reference to its own parent and there was a known way to walk children at any level, then it could be possible to write code to construct a path like you've said, but you'd have to be a lot more specific about what exactly these objects were and how you find out which child index a given object is.
For example, if these were DOM objects which meets both of the criteria (child contains reference to parent and there's a known way to navigate the children of any given object) and you wanted the root parent to be document.body
, then you could do this:
function getSiblingPosition(obj) {
var siblings = obj.parentNode.children;
var elemCnt = 0;
for (var i = 0; i < siblings.length; i++){
if (siblings[i] === obj) {
return elemCnt;
} else {
if (siblings[i].nodeType === 1) {
++elemCnt;
}
}
}
}
function getPath(obj) {
var path = "";
while (obj && obj !== document.body) {
var cnt = getSiblingPosition(obj);
path = ".children[" + cnt + "]" + path;
obj = obj.parentNode;
}
path = "document.body" + path;
return path;
}
Working demo: https://jsfiddle.net/jfriend00/8w9v8kpf/
Upvotes: 1