0

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 ?

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use reduce and get access to the key and value of each result, evaluate them and push it to the new object. Here's how:

let filteredResults = _.reduce(results, (result, value, key) => {
    if (value.length > 0) {
        result[key] = value;
    }
    return result;
}, {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.