ReactHustle

How to remove null or undefined from a nested object in Javascript

Jasser Mark Arioste

Jasser Mark Arioste

How to remove null or undefined from a nested object in Javascript

Sometimes we need to remove null or undefined properties from an object in JavaScript. Maybe to clean the data from the server or to pass clean data to the server or database.

Remove null/undefined properties using pure JavaScript #

To remove null or undefined properties from an object using vanilla JavaScript, we can use a combination of Object.entries and array.filter  and recursion.

//index.js

const data = {
  prop1: 'hello',
  prop2: undefined,
  prop3: null,
  prop4: {
    innerProp: null,
    innerProp2: 'world',
  },
};

function removeEmpty(data) {
  //transform properties into key-values pairs and filter all the empty-values
  const entries = Object.entries(data).filter(([, value]) => value != null);

  //map through all the remaining properties and check if the value is an object.
  //if value is object, use recursion to remove empty properties
  const clean = entries.map(([key, v]) => {
    const value = typeof v == 'object' ? removeEmpty(v) : v;
    return [key, value];
  });

  //transform the key-value pairs back to an object.
  return Object.fromEntries(clean);
}

const clean = removeEmpty(data);

console.log(clean); //{"prop1":"hello","prop4":{"innerProp2":"world"}}
123456789101112131415161718192021222324252627282930

The good thing about the method above is it does not modify the old object and instead returns us a new object.

Conclusion #

We have successfully created a function to remove null or undefined properties from a deeply nested object in javascript.

If you like tutorials like these, please leave a like or consider subscribing to our newsletter down below!

Credits: Image by MF Gallery from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle