Skip to content

Instantly share code, notes, and snippets.

@aichholzer
Created February 7, 2018 21:59
Show Gist options
  • Select an option

  • Save aichholzer/ea2a8d34cb579cb2911cb9a9f2aaf085 to your computer and use it in GitHub Desktop.

Select an option

Save aichholzer/ea2a8d34cb579cb2911cb9a9f2aaf085 to your computer and use it in GitHub Desktop.

Revisions

  1. aichholzer created this gist Feb 7, 2018.
    35 changes: 35 additions & 0 deletions clean.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    const sample = {
    a: 'Hello',
    b: '', // Will be removed
    c: null,
    d: {
    a: 1,
    b: '', // Will be removed
    c: 3,
    d: {
    a: 1,
    b: '', // Will be removed
    c: 'world'
    },
    e: null
    }
    }

    /**
    * Attach the cleaning method to the object's prototype chain.
    */
    Object.defineProperties(Object.prototype, {
    clean: {
    configurable: true,
    enumerable: false,
    value: function clean (obj = this) {
    Object.keys(obj).forEach(key => obj[key] !== null && typeof obj[key] === 'object' ? clean(obj[key]) :
    obj[key] === '' && delete obj[key]);

    return obj;
    }
    }
    });

    const cleanObject = sample.clean();
    console.log(JSON.stringify(cleanObject, null, 2));