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

时间:2014-10-20 00:08:05

标签: javascript node.js serialization

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

E.g。

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

输出:

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

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

1 个答案:

答案 0 :(得分:3)

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);
    });
}
相关问题