[英]Node.js all properties of object to strings
How can I convert all object properties to strings like they would be paths? 如何将所有对象属性转换为字符串,就像路径一样?
Eg 例如
{a:{s:"asd",g:"asd"}, b:2}
Output: 输出:
["a.s",
"a.g",
"b"]
Does exist a function able to do something like this? 是否存在能够执行此类操作的功能?
There isn't one built into Node, but it's not hard to write recursively: 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.