How to remove empty values from object using lodash

一个人想着一个人 提交于 2019-12-01 18:02:49

You can achieve this through several steps:

  1. Use pickBy() to pick object key-values, using the isObject() predicate.

  2. Use mapValues() to recursively call removeEmptyObjects(), note that it would only invoke this function with objects.

  3. Remove all empty objects that are found after the mapValues() using omitBy() with an isEmpty() predicate.

  4. Assign all primitive values from the object all over again using assign() for assignment, and omitBy() with an isObject() predicate.


function removeEmptyObjects(obj) {
  return _(obj)
    .pickBy(_.isObject) // pick objects only
    .mapValues(removeEmptyObjects) // call only for object values
    .omitBy(_.isEmpty) // remove all empty objects
    .assign(_.omitBy(obj, _.isObject)) // assign back primitive values
    .value();
}

function removeEmptyObjects(obj) {
  return _(obj)
    .pickBy(_.isObject)
    .mapValues(removeEmptyObjects)
    .omitBy(_.isEmpty)
    .assign(_.omitBy(obj, _.isObject))
    .value();
}

_.mixin({
  removeEmptyObjects: removeEmptyObjects
});

var template = {
  node: "test",
  representation: {
    range: {}
  },
  transmit: {
    timeMs: 0
  }
};

var result = _.removeEmptyObjects(template);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

You could use _.pick to choose only the properties you want, as in

var desiredTemplate = _.pick(template, ['node','transmit']); 

Otherwise, as far as I can tell, lodash has nothing built in that can recursively remove empty objects/arrays from an object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!