如何使用lodash过滤器从未定义值的javascript对象中删除属性?

时间:2017-09-06 18:57:51

标签: javascript filter lodash

我正在尝试将以下代码转换为使用lodash _.filter

的代码
var substitutionValues = { one: "hi", two: undefined, three: 3};
var keys = _.keys(substitutionValues);

for (var i = 0; i < keys.length; i++) {
  if (substitutionValues[keys[i]] === undefined) {
    delete substitutionValues[keys[i]];
  }
}

// => { one: "hi", three: 3 }

请注意我不想使用lodash的_.reduce,_.pick或_.omit。

1 个答案:

答案 0 :(得分:1)

您可以使用_.pickBy()作为对象的过滤器。由于_.pickBy()的默认谓词是_.identity,因此它会过滤任何虚假值(第一个示例)。如果您想更具体,请相应地定义回调(第二个示例):

&#13;
&#13;
var substitutionValues = { one: "hi", two: undefined, three: 3, four: null };

/** 1st example **/
var widthoutAllFalsyValues = _.pickBy(substitutionValues);

console.log(widthoutAllFalsyValues);

/** 2nd example **/
var widthoutUndefined = _.pickBy(substitutionValues, _.negate(_.isUndefined));

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

要使用过滤器,您必须使用_.entries()之类的东西(保留键)将对象转换为数组,然后过滤条目,并缩减回对象: / p>

&#13;
&#13;
var substitutionValues = { one: "hi", two: undefined, three: 3, four: null };

var result = _(substitutionValues)
  .entries()
  .filter(([k, v]) => !_.isUndefined(v))
  .reduce((o, [k, v]) => {
    o[k] = v;
    return o;
  }, {});
  
console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;