如何在js中将对象转换为文本

时间:2013-06-26 14:30:03

标签: javascript object

这是一个js对象,它表示我正在处理的命令行os项目中的文件系统:

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

当我运行时,我得到了

"hi"

如何将其显示为

/1/hi/

我需要获取当前所选对象的“文件路径”。

3 个答案:

答案 0 :(得分:3)

制作某种查找功能

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));

使用它

console.log(lookup('1', 'hi').path); // "/1/hi"

答案 1 :(得分:0)

您的代码返回"hi" var currentDir = obj[1].hi;

也是如此

答案 2 :(得分:0)

您在访问对象时已经知道了路径。做这样的事情:

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

您可以在for循环,each循环while等中使用此功能,或者像您的示例一样直接访问。