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:
Admin Dirask Community
4380

Quick solution (ES6+):

Reusable arrow function

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

 

References

  1. Object.entries() - JavaScript | MDN
  2. Object.fromEntries() - JavaScript | MDN
  3. Array.prototype.filter() - JavaScript | MDN
  4. Array.prototype.map() - JavaScript | MDN
0 commentsAdd 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