我正在尝试创建一个递归函数来过滤对象,具体取决于第二个传递参数中的属性。
过滤效果很好,但我的数组被替换为空对象。我可以做些什么来避免这种情况发生?
var filter = function(obj, fields) {
var key, o;
if (typeof obj !== "object") { return obj;}
o = {};
for (key in obj) {
if (fields[key]) {
o[key] = filter(obj[key], fields[key]);
}
}
return o;
};
data = {name: "John Doe", followers: [], notAllowedProp: false}
allowedFields = {name: true, followers: true}
console.log(filter(data, allowedFields));
// => Object { name: "John Doe", followers: {}}