如何使用lodash从对象中删除空值 [英] How to remove empty values from object using lodash

查看:1402
本文介绍了如何使用lodash从对象中删除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个属性的对象,我想使用lodash删除空的对象/嵌套对象.最好的方法是什么?

I have an object with several properties and I would like to remove objects/nested objects that are empty, using lodash. What is the best way to do this?

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

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

我尝试过类似的操作,但我迷路了.

I tried something like this, but I am lost.

Utils.removeEmptyObjects = function(obj) {
  return _.transform(obj, function(o, v, k) {
    if (typeof v === 'object') {
      o[k] = _.removeEmptyObjects(v);
    } else if (!_.isEmpty(v)) {
      o[k] = v;
    }
  });
};
_.mixin({
  'removeEmptyObjects': Utils.removeEmptyObjects
});

推荐答案

您可以通过以下几个步骤来实现:

You can achieve this through several steps:

  1. 使用 isObject()谓词.

使用 mapValues()递归调用removeEmptyObjects(),请注意,它只会调用此功能带有对象.

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

使用 omitBy()删除mapValues()之后找到的所有空对象.一个 isEmpty()谓词.

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

使用 assign()重新分配对象中的所有原始值,和omitBy()带有isObject()谓词.

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>

这篇关于如何使用lodash从对象中删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆