Skip to content Skip to sidebar Skip to footer

How To Make An Object Into Text In Js

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': {

Solution 1:

Make some kind of lookup function

var lookup = (function (o) {
    returnfunctionlookup() {
        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"

Solution 2:

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

Solution 3:

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.

Post a Comment for "How To Make An Object Into Text In Js"