I am trying to create a recursive function that filters an object, depending on the properties in the second passed argument.
Filtering works well, but my arrays are being replaced with empty objects. What could I do different so that this doesn’t occur?
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: {}}