如何使用lodash递归地从JSON中删除空对象

时间:2017-06-28 15:06:32

标签: javascript arrays json lodash

var template = {
    personal: {},
    education: {},
    certificate: [{"test": "Test"}, {}, {}],
    experience: []
}

removeEmptyObj(template);

function removeEmptyObj(obj)
for (var key in obj) {
    console.log("Foor Loop" + key + " " + obj[key]);
    if (_.isObject(obj[key]) && !_.isEmpty(obj[key])) {
        console.log("Second Loop Object:::" + key + " " + obj[key]);
        removeEmptyObj(obj[key]);
    }
    if (_.isEmpty(obj[key])) {
        console.log("Delete Object:::" + key + " " + obj[key]);
        obj = _.omitBy(obj, _.isEmpty);
    }
}
console.log(obj);
return obj;
}

当前输出为:{certificate: [{"test": "Test"}, {}, {}]}

所需输出:{certificate: [{"test": "Test"}]}

这里有什么错误你的帮助欣赏:)

5 个答案:

答案 0 :(得分:5)

您可以递归_.transform()对象到新对象,并在途中清理空对象和数组。

注意:我在结构中添加了更多元素以进行演示

var template = {
    personal: {},
    education: {},
    certificate: [{}, {"test": "Test"}, {}, {}, [{}], [{}, 1, []]],
    experience: [[1, 2, [], { 3: [] }]]
};

function clean(el) {
  function internalClean(el) {
    return _.transform(el, function(result, value, key) {
      var isCollection = _.isObject(value);
      var cleaned = isCollection ? internalClean(value) : value;

      if (isCollection && _.isEmpty(cleaned)) {
        return;
      }

      _.isArray(result) ? result.push(cleaned) : (result[key] = cleaned);
    });
  }

  return _.isObject(el) ? internalClean(el) : el;
}

console.log(clean(template));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 1 :(得分:1)

不需要Lodash。一个简单的过滤器就可以了。

var template = {
    personal: {},
    education: {},
    certificate: [{"test": "Test"}, {}, {}],
    experience: []
}

template.certificate = template.certificate.filter(o => Object.keys(o).length)

console.log(template.certificate)

答案 2 :(得分:1)

您可以使用此功能,区分普通对象和数组:

// Helper function
var isEmptyObject = _.overEvery(_.isObject, _.isEmpty);
// Actual function
function removeEmptyObj(obj) {
    return  _.isArray(obj)  ? _.reject(_.map(obj, removeEmptyObj), isEmptyObject)
          : _.isObject(obj) ? _.omitBy(_.mapValues(obj, removeEmptyObj), isEmptyObject)
          : obj; 
}

// Example
var template = {
    personal: {},
    education: {},
    certificate: [{"test": "Test"}, {}, {}],
    experience: []
}

var result = removeEmptyObj(template);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

答案 3 :(得分:0)

您是否尝试过_.omit(证书,[{}])。我从来没有尝试但让我知道

答案 4 :(得分:0)

您可以尝试这种方法,它适用于您的示例。我很确定我们可以用更好的lodash方式做,但至少你要解除阻止

deepOmit(obj) {
    function omitFromObject(obj) {
        return _.transform(obj, function(result, value, key) {
            if (_.isNull(value) || _.isUndefined(value) || _.isEmpty(value)) {
                return;
            }

            result[key] = _.isObject(value) ? omitFromObject(value) : value;
        });
    }

    return omitFromObject(obj);
}