使用角度2中的loadsh以递归方式从json对象中删除空白对象和数组

时间:2017-09-01 08:24:20

标签: angular lodash

我尝试使用angular2中的lodash从json对象中删除所有空白对象和数组对象,但不能在对象中正确解析。

我的Json对象:

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

尝试删除使用方法

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;
 }

我的输出:

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

预期输出:

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

1 个答案:

答案 0 :(得分:0)

而不是复杂的递归,并改变其中的tje对象,你可以对Object进行字符串化,让你回调(JSON.parse的第二个参数)在从字符串中解析它时进行递归,以删除属性只需返回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));

然而,代码可以更好,我只是根据您的要求即时编写。