-1

I am trying to convert the following code to something that uses the 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 }

Please note I do not want to use lodash's _.reduce, _.pick, or _.omit.

morrime
  • 463
  • 9
  • 18
  • You might want to check out `pickBy`. You can specify a condition while iterating over object properties, and use that to filter keys that are undefined. https://lodash.com/docs/4.17.4#pickBy – Wolfie Sep 06 '17 at 19:00
  • 2
    that would be a terrible use case for filter – Marcin Malinowski Sep 06 '17 at 19:00
  • Also check out this related stackoverflow post: https://stackoverflow.com/questions/30726830/how-to-filter-keys-of-an-object-with-lodash – Wolfie Sep 06 '17 at 19:01
  • @MarcinMalinowski I realize it's not a good use case, but nonetheless I would like to know how to do it. I already know about lodash's pickBy and omitBy. – morrime Sep 06 '17 at 19:04

1 Answers1

1

You can use _.pickBy() as a filter for objects. Since the default predicate of the _.pickBy() is _.identity it will filter any falsy value (1st example). If you want to be more specific, define the callback accordingly (2nd example):

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

To use filter you'll have to convert the object into an array by the use of something like _.entries() (to preserve the keys), then filter the entries, and reduce back to an object:

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209