繁体   English   中英

Node.js将对象的所有属性转换为字符串

[英]Node.js all properties of object to strings

如何将所有对象属性转换为字符串,就像路径一样?

例如

{a:{s:"asd",g:"asd"}, b:2}

输出:

["a.s",
 "a.g",
 "b"]

是否存在能够执行此类操作的功能?

Node中没有内置的,但递归写入并不困难:

function descendants(obj) {
    return Object.keys(obj).map(function (key) {
        var value = obj[key];

        // So as to not include 'a'; a bit of a hack.
        // You might need better criteria.
        if (typeof value === 'object') {
            return descendants(value).map(function (desc) {
                return key + '.' + desc;
            });
        }

        return [key];
    }).reduce(function (a, b) {
        return a.concat(b);
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM