M4rk
M4rk

Reputation: 2272

Node.js all properties of object to strings

How can I convert all object properties to strings like they would be paths?

E.g.

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

Output:

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

Does exist a function able to do something like this?

Upvotes: 1

Views: 54

Answers (1)

Ry-
Ry-

Reputation: 225105

There isn’t one built into Node, but it’s not hard to write recursively:

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

Upvotes: 3

Related Questions