js中如何将一个对象变成文本 [英] How to make an object into text in js

查看:218
本文介绍了js中如何将一个对象变成文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

如何让它显示为

/1/hi/

我需要获取当前选择对象的文件路径".

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

推荐答案

做某种查找功能

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"

这篇关于js中如何将一个对象变成文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆