What's the best way to deduce keys with invalid (NaN, empty, etc.) values ​​from an object?

I have a small search form that a user fills out. There will be several searches that will go into MongoDB:

The form creates a variable named searchParams

, which might look like this:

var searchParams = {
  city: "Springfield",
  bedrooms: 3,
  bathrooms: 2
};

      

Then I have a function that takes searchParams as an argument and queries Mongo using it:

var searchListings = function(searchParams){
  return db.MyListings.find(searchParams).fetch();
}

db.MyListings.find( {city: "Springfield", bedrooms: 3, bathrooms: 2} ).fetch();

      

This is fine and useful for a complete object searchParams

, but if the user does not fill out parts of the form and the object turns out to be like this:

var searchParams = {
  city: "",
  bedrooms: NaN,
  bathrooms: 3
};

      

The request ends with an error. He's trying to literally look for a property with a town "" and a NaN bedroom.

What I want the request to be in the case of this object is simply:

  db.MyListings.find( {bathrooms: 3} ).fetch();

      

I can go through each key one by one and check the "NaN" conditions and conditions and somehow remove the key from the object searchParams

(I think I'm kind of sterilizing the object?), But I was wondering if there was a smarter way to deduce keys with invalid values?

I have it installed underscore

.

UPDATE: This project is currently using Meteor 0.9.1. Meteor uses Underscore 1.0.0, so below doesn't work:

The following doesn't work:

searchParams = {
  bathrooms: 3,
  bedrooms: NaN,
  city: "",
  exteriorSize: NaN,
  interiorSize: NaN,
  price: 0
};

console.log(searchParams);

newSearchParams = _.omit(searchParams, function(val) { 
  return !val;
});

console.log(newSearchParams); // exactly the same as searchParams

      

And if I do this:

searchParams = {
  bathrooms: 3,
  bedrooms: NaN,
  city: "",
  exteriorSize: NaN,
  interiorSize: NaN,
  price: 0
};

console.log(searchParams);

newSearchParams = _.pick(searchParams, function(val) { 
  return !!val;
});

console.log(newSearchParams); // blank object

      

+2


source to share


1 answer


With, underscore 1.7.0+

you can easily filter the request object with _. pick () :

searchParams = _.pick(searchParams, function(val) { 
  return !!val;
});

      

..., which will create an object with only those properties that have been assigned valid values.

You can do the same thing in a slightly different way with _. omit () :

searchParams = _.omit(searchParams, function(val) { 
  return !val;
});

      



In this case, all properties with fake values ​​will be omitted.


For completeness of radius, here's the vanilla JS path:

var filteredSearchParams = {};
for (var prop in searchParams) {
  if (searchParams.hasOwnProperty(prop) && !!searchParams[prop]) {
    filteredSearchParams[prop] = searchParams[prop];
  }
}

      

+3


source







All Articles