Search code examples
javascriptarrayslodash

lodash: filter objects with value of non empty array


I am new to lodash, and I am writing a line that returns objects that has non-empty array as values (excluding the empty array values);

let results = {"1":[1,2,3],"2":[2,4,6],"0":[]};
let filteredResults = _.filter(results, (result) => {return (_.size(_.values(result)) > 0);});
console.log(filteredResults);

My expected value of filteredResults is: {'1': [ 1, 2, 3 ], '2': [ 2, 4, 6 ] }. However I am getting the result of [ [ 1, 2, 3 ], [ 2, 4, 6 ] ].

Where are the keys 1 and 2 ?


Solution

  • The _.filter method can accept an object as its first argument, but it will just return an array with the accepted values from the original object. You probably want to use the _.pickBy method instead, which will return an object with the key/value pairs that pass the filter:

    let filteredResults = _.pickBy(results, value => value.length > 0)