Node.js - Remove null elements from JSON object

I am trying to remove null/empty elements from JSON objects, similar to the functionality of the python webutil/util.py -> trim_nulls method. Is there something built in to Node that I can use, or is it a custom method.

Example:

var foo = {a: "val", b: null, c: { a: "child val", b: "sample", c: {}, d: 123 } };

Expected Result:

foo = {a: "val", c: { a: "child val", b: "sample", d: 123 } };

I don't know why people were upvoting my original answer, it was wrong (guess they just looked too quick, like I did). Anyway, I'm not familiar with node, so I don't know if it includes something for this, but I think you'd need something like this to do it in straight JS:

var remove_empty = function ( target ) {

  Object.keys( target ).map( function ( key ) {

    if ( target[ key ] instanceof Object ) {

      if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') {

        delete target[ key ];

      }

      else {

        remove_empty( target[ key ] );

      }

    }

    else if ( target[ key ] === null ) {

      delete target[ key ];

    }

  } );


  return target;

};

remove_empty( foo );

I didn't try this with an array in foo -- might need extra logic to handle that differently.

You can just filter with a for loop and output to a new clean object:

var cleanFoo = {};
for (var i in foo) {
  if (foo[i] !== null) {
    cleanFoo[i] = foo[i];
  }
}

If you need to process children objects too you'll need recursion.

Thanks for all the help.. I've pieced the following code using the feedback in all of the comments which works with foo.

function trim_nulls(data) {
  var y;
  for (var x in data) {
    y = data[x];
    if (y==="null" || y===null || y==="" || typeof y === "undefined" || (y instanceof Object && Object.keys(y).length == 0)) {
      delete data[x];
    }
    if (y instanceof Object) y = trim_nulls(y);
  }
  return data;
}