0

I am try to remove all blank object and array object subsequently from my json object using lodash in angular2 but not parse properly in object.

My Json Object:

{
  "personal": {
    "strenths": {},
    "books": [{},{},{"Perority1": "Test","level": ""},{"Perority2": "","level": ""},{"courses": [{},{},{}]}]
  },
  "eduction": [{},{},[{}]]
};

Try to remove using method

clean(obj) {
     console.log("Enter in a Clean() Method::::");
     Object.keys(obj).forEach(key => {
         if ($.isArray(obj[key])) {
             obj[key] = $.remove(obj[key], function(n) {
                 if ($.isObject(n) && (n === null || n === undefined || $.isEmpty(n))) {
                     return false;
                 } else {
                     return true;
                 }
             });
             console.log("After Change Array:::::" + JSON.stringify(obj[key]));
             if (obj[key] === null || obj[key] === undefined || $.isEmpty(obj[key])) {
                 delete obj[key];
             } else {
                 this.clean(obj[key]);
             }

         } else if ($.isObject(obj[key])) {

             if (obj[key] === null || obj[key] === undefined || $.isEmpty(obj[key])) {
                 delete obj[key];
             } else {
                 this.clean(obj[key]);
             }
         }
     });
     return obj;
 }

My Output:

{"personal":{"books":[{"Perority1":"Test","level":""},{"Perority2":"","level":""},{}]},"eduction":[null]}

Expected Output:

{"personal":{"books":[{"Perority1":"Test","level":""},{"Perority2":"","level":""}]}}
Bipin
  • 51
  • 3

1 Answers1

0

Instead of a complicated recursion, and altering tje object inside that, You can stringify the Object, and let you callback (the 2nd parameter of JSON.parse) do the recursion while parsin it from string, to remove a property simply return undefined;

var data = {
  "personal": {
    "strenths": {},
    "books": [{},{},{"Perority1": "Test","level": ""},{"Perority2": "","level": ""},{"courses": [{},{},{}]}]
  },
  "eduction": [{},{},[{}]]
};

data = JSON.parse(JSON.stringify(data), function(k, v){
    if (Array.isArray(v)) {
        var fArr = v.filter(e=>e);
        return fArr.length && fArr || undefined;
    } else if(typeof(v) === "object" && !Object.keys(v).length) {
        return undefined;
    } else {return v};
});

console.log(JSON.stringify(data));

However the code can be better, I just wrote on the fly on basis of your requirement.

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32