-2

Here is a js object that represents the file system in the command line os project I'm working on:

var obj = {
        "1": {
            "hi": "hi"
        }, 
        "2": {
            "bye": "bye"
         }
    };
var currentDir = obj["1"]["hi"];
console.log(currentDir);

When I run this, I get

"hi"

How do I get this to appear as

/1/hi/

I need to get the "file path" of the currently select object.

12
  • 2
    Your code logs "hi" when I run it, not "[object Object]". Commented Jun 26, 2013 at 14:31
  • 1
    @Chase Welcome to StackOverflow. It's not very clear what you're trying to do, because it doesn't seem like you have an understanding of the language constructs that you're using. I recommend doing some reading about javascript objects and arrays, and the accessors for each. When you have a better understanding, come back and revise your question. Commented Jun 26, 2013 at 14:34
  • 1
    @Chase: That is fundamentally impossible. The same string can be referenced by multiple objects. You need to re-think your design. Commented Jun 26, 2013 at 14:37
  • 1
    @Chase, as you're entering "1" and "hi" manually, why can't you just do "1" + "/" + "hi" + "/"? Commented Jun 26, 2013 at 14:39
  • 1
    Don't you already know the path when you address the object? do something like console.log(firstIndex + '/' + secondIndex + '/ + obj[firstIndex][secondIndex]); Commented Jun 26, 2013 at 14:43

3 Answers 3

3

Make some kind of lookup function

var lookup = (function (o) {
    return function lookup() {
        var i, e = o, s = '';
        for (i = 0; i < arguments.length; ++i) {
            s += '/' + arguments[i];
            if (!e.hasOwnProperty(arguments[i]))
                throw "PathNotFoundError: " + s;
            e = e[arguments[i]];
        }
        return {path: s, value: e};
    }
}(obj));

And using it

console.log(lookup('1', 'hi').path); // "/1/hi"
Sign up to request clarification or add additional context in comments.

Comments

0

Your code returns "hi" So does var currentDir = obj[1].hi;

1 Comment

I need to get the path of objects to the current object
0

You already know the path when you access your object. do something like this:

console.log(firstIndex + '/' + secondIndex + '/ + obj[firstIndex][secondIndex]);

you can use this in for loops, each loops while etc.. or by direct access like your example.

Comments

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.