Reputation: 2272
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
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