Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active December 30, 2015 12:17
Show Gist options
  • Save khoand0000/ac5b73e6c58652c2cb8b to your computer and use it in GitHub Desktop.
Save khoand0000/ac5b73e6c58652c2cb8b to your computer and use it in GitHub Desktop.
filter object with preserve keys

I have a object

var obj = {
  1: [5, 7, 8],
  7: [4, 2],
  10: [],
  19: [4]
}; // each key:value is id: array

I want to filter the object: remove keys have empty array and preserve keys. If I use _.filter, result is not expected:

_.filter(obj, function(ids) { return ids.length > 0;});
_.filter(obj, _.negate(_.isEmpty)); // or the code

// result is
// {
//  [5, 7, 8],
//  [4, 2],
//  [4],
// }

But I want expected result is

{
  1: [5, 7, 8],
  7: [4, 2],
  19: [4]
}

There are 2 ways:

  1. short code. I'm using it, of course
_.pick(obj, _.negate(_.isEmpty));
  1. long code. Just reference.
_.chain(obj)
.pairs()
.filter(function(value){ return !_.isEmpty(value[1]);})
.object()
.value()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment