CodeChimp
CodeChimp

Reputation: 8154

Determine if an Object in Javascript has any properties

I have an object that looks like this:

var searchFilter = {_id: XXX, approved: true}

Which is used to drive a Meteor collection search filter. I then have a pair of text boxes that allow the user to enter in a range of dates, in which case I update the filter to trigger Meteor to reactively re-run the filter, like so:

// Some Meteor event-handler...
  var val = // code to pull val in...not important...
  var searchFilter = Session.get('searchFilter');
  if (!val || val === '') {
    delete searchFilter.created_on;
  } else {
    searchFilter.created_on = {$gte: new Date(val)};
  }
  Session.set('searchFilter', searchFilter);

The else that removes the create_on child object works great for one field, but in my code I have two fields, one for a beginning range and one for an ending range. What I need to be able to do is remove the created_on: {$gte}, then check if created_on is "empty", and if so, remove the whole thing. I am not sure how I go about doing that, though. Is this possible? I have access to jQuery and underscore.js as libraries, if that helps.

Upvotes: 0

Views: 38

Answers (1)

Rhumborl
Rhumborl

Reputation: 16609

You can use Object.getOwnPropertyNames to see if any properties have been defined on an object. This will return an array of property names, so just check is it's length is greater than 0.

// create the filter with $gte set
var searchFilter = {};
searchFilter.created_on = {$gte: new Date(56378563786)};

//  check if any properties are defined
var hasProps = Object.getOwnPropertyNames(searchFilter.created_on).length > 0;
alert("Has properties: " + hasProps);

// now delete $gte

delete searchFilter.created_on.$gte;

//  check if any properties are defined
var hasProps = Object.getOwnPropertyNames(searchFilter.created_on).length > 0;
alert("Has properties: " + hasProps);

Upvotes: 1

Related Questions