Industrial
Industrial

Reputation: 42758

What am I doing wrong in my recursive javascript function?

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: {}}

Upvotes: 2

Views: 499

Answers (2)

voithos
voithos

Reputation: 70552

Try this on a console:

> typeof []
"object"

To check for an array more robustly, you can use Object.prototype.toString:

> Object.prototype.toString.call([])
"[object Array]"

Object.prototype.toString has well-defined behavior for all native objects, and is quite reliable. Thus, for example, if you want to return anything that is not a "true" object, you could write:

if (Object.prototype.toString(obj) !== "[object Object]") {
    return obj;
}

Upvotes: 1

Peter Olson
Peter Olson

Reputation: 142921

Arrays have type object. Consequently, you'll need to edit this line if you want to return early for arrays:

if (typeof obj !== "object") { return obj; } 

There are many ways to check for an array, but this is what I would do:

if(typeof obj !== "object" && !(obj instanceof Array)) { return obj; } 

Upvotes: 1

Related Questions