DEV Community

Discussion on: Purging unwanted properties in js object

Collapse
alwarg profile image
Alwar G Author • Edited on

@bharathpanchak Thank you for poiniting out my mistake.
I tried one solution

function getPurgedObj(obj){
      let stringfiedObj = JSON.stringify(obj, (key, value) => {
        if (Array.isArray(value)) {
          value = value.filter((val) => !['', null].includes(val));
        }
        return ['', null].includes(value) || (typeof value === 'object' &&(value.length === 0 || Object.keys(value).length === 0)) ? undefined : value;
      });
      let resObj = JSON.parse(stringfiedObj);
      let isEmptyPropsPresent = ['{}', '[]', '""', 'null'].some((key) => stringfiedObj.includes(key))
      if(isEmptyPropsPresent) {
        return getPurgedObj(resObj);
      }
      return resObj;
    }
Enter fullscreen mode Exit fullscreen mode

Please share if you have better solution