0

To remove empty rows from an object, require a generic solution.

The object has contain a list.

This is a sample object that i want to check

  {
    "test": {
      "id": null
    },
    "testName": null,
    "specimen": {
      "id": null
    },
    "specimenName": null,
    "collectionDate": null,
    "resultDate": null,
    "result": null,
    "finding": null,
    "resultValue": null
  }

I had tried this, but it will not work when there is a list inside.

purgeEmptyRows(obj: any) : boolean {
      let isEmpty = false;
      Object.keys(obj).forEach(key => {
          if (!obj[key]) {
              isEmpty = false;
          }else {
            return true;
          } 
      })
     return isEmpty;
}
user630209
  • 1,123
  • 4
  • 42
  • 93

1 Answers1

0

Try this one,

this.findAndReplace(obj, null, []);    

findAndReplace(obj: any, value: any, replacevalue: any) {           
    for (var x in obj) {
        if (obj.hasOwnProperty(x)) {
            if (typeof obj[x] == 'object') {
                this.findAndReplace(obj[x], value, replacevalue);
            }
            if (obj[x] == value) { 
                obj[x] = replacevalue;
                // break; // uncomment to stop after first replacement
            }
        }
    }
    console.log(JSON.stringify(obj));
}
hrdkisback
  • 898
  • 8
  • 19
  • This recursive logic can use. To check whether this objects all elements are null, then return false, else true this is what my question about. No find and replace. – user630209 Oct 02 '19 at 17:05
  • Ohh! my bad..Actually you have mentioned "Remove null elements from an Object" in question title that's why I got confused. – hrdkisback Oct 04 '19 at 06:44