0

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";
}

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation and help.
@americanknight - If this post answered your question, then you can indicate that to the community by clicking the green checkmark to the left of the answer. This will also earn you some reputation points for following the desired procedure. If it did not answer your question, then please explain what is not yet answered.

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.