Languages

JavaScript - removing undefined fields from object

0 points
Asked by:
telsa
502

How can I remove properties from object that are undefined or null?

1 answer
0 points
Answered by:
telsa
502

Quick solution (ES6+):

const newObject = Object.fromEntries(Object.entries(myObject).filter(([_, value]) => value != null));

Reusable arrow function

// ONLINE-RUNNER:browser;

const removeBlank = (inputObject) => {
    return Object.fromEntries(
        Object.entries(inputObject).filter(([_, value]) => value != null)
    );
}


// Usage example:

const myObject = { a: 1, b: '', c: undefined, d: null };

const newObject = removeBlank(myObject);

console.log(JSON.stringify(newObject)); // { a: 1, b: '' }

Explanation:

To remove properties that are undefined or null we used the following methods:

  • Object.entries() - to get array of a given object's properties ([key, value] pairs),
  • filter() - to remove properties that values are null or undefined,
  • Object.fromEntries() - to create a new result object from filtered [key, value] pairs.

Recursion to remove properties from nested objects

// ONLINE-RUNNER:browser;

const removeBlank = (inputObject) => {
    return Object.fromEntries(
        Object.entries(inputObject)
            .filter(([_, value]) => value != null)
            .map(([key, value]) => [
                key,
                value === Object(value) ? removeBlank(value) : value,
            ])
    );
};


// Usage example:

const myObject = {
    a: 1,
    b: { b1: undefined },
    c: { c1: null },
};

const newObject = removeBlank(myObject);

console.log(JSON.stringify(newObject, null, 4)); // { a: 1, b: {}, c: {} }

 

References

  1. Object.entries() - JavaScript | MDN
  2. Object.fromEntries() - JavaScript | MDN
  3. Array.prototype.filter() - JavaScript | MDN
  4. Array.prototype.map() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join