Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

1 of 2
bharath muppa
  • 1.1k
  • 13
  • 30

I have same scenario in my project and achieved using following method.

It works with all data types, few mentioned above doesn't work with date and empty arrays .

removeEmptyKeysFromObject.js

removeEmptyKeysFromObject(obj) {
 Object.keys(obj).forEach(key => {
 if (Object.prototype.toString.call(obj[key]) === '[object Date]' && obj[key].toString().length === 0) {
 delete obj[key];
 } else if (obj[key] && typeof obj[key] === 'object') {
 this.removeEmptyKeysFromObject(obj[key]);
 } else if (obj[key] == null || obj[key] === "") {
 delete obj[key];
 }
 if (obj[key] && typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0 && Object.prototype.toString.call(obj[key]) !== '[object Date]') {
 delete obj[key];
 }
 });
 return obj;
}

pass any object to this function removeEmptyKeysFromObject()

bharath muppa
  • 1.1k
  • 13
  • 30

AltStyle によって変換されたページ (->オリジナル) /