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:
- short code. I'm using it, of course
_.pick(obj, _.negate(_.isEmpty));
- long code. Just reference.
_.chain(obj)
.pairs()
.filter(function(value){ return !_.isEmpty(value[1]);})
.object()
.value()