Underscore.js / Lodash Mixin to deep compact an object

// returns a copy of the original object from which all empty keys, objects and arrays have been deleted // currently, it's only meant to work with objects that could have been created by JSON.parse // See here for Copyright: https://gist.github.com/kurtmilam/886b705fb0eb03001c77

JavaScript

// returns a copy of the original object from which all empty keys, objects and arrays have been deleted
// currently, it's only meant to work with objects that could have been created by JSON.parse

// See here for Copyright: https://gist.github.com/kurtmilam/886b705fb0eb03001c77
// Thanks to ljharb ( https://github.com/ljharb ) for the tips

function deepCompact (object) {

  var oType = typeof object
  if (object !== null && oType != 'undefined') {
    if ((object instanceof Object || Array.isArray(object))
        && !(object instanceof Date)) {
      var ret
      if (object instanceof Array) {
        ret = object.map(function (val, key, col) {
          return deepCompact(val)
        })
        if (ret.length > 0) {
          return ret
        }
      } else {
        var keys = Object.keys(object)
        ret = keys.reduce(function (acc, val, key) {
          var tmp = deepCompact(object[val])
          if (typeof tmp != 'undefined') {
            acc[val] = tmp
          }
          return acc
        }, {})
        if (typeof ret == 'object' && Object.keys(ret).length > 0) {
          return ret
        }
      }
    } else if (oType == 'string' || oType == 'boolean' || oType == 'number') {
      return object
    } else if (object instanceof Date) {
      return String(object)
    } else if (!(object instanceof Object) && !(object instanceof Array)) {
      return typeof object
    }

}
 
console.clear()
 
_.mixin({ deepCompact: deepCompact })
 
var input = {a:1,b:{c:[],d:{}},f:new Date(),g:function(){},h:[1]}
 
var result = deepCompact(input)
 
console.log(input)
//-> Object {a: 1, b: Object, f: Sat Aug 02 2014 22:23:41 GMT+0200 (W. Europe Daylight Time), g: function, h: Array[1]}
  
console.log(result)
//-> Object {a: 1, f: "Sat Aug 02 2014 22:23:41 GMT+0200 (W. Europe Daylight Time)", g: "function", h: Array[1]}
 

// (all the action takes place in the console)