Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter object based on conditional argument?

I am calling a function with two arguments,

Arg 1: Object {a:1, b:2, c:3, d:4}

Arg 2: Condition ((prop, key) => prop >= 3))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here based on the condition we need to filter the object and provide the result as array of objects.

The code that I have tried,

const pickBy = (a, b) => {
  const data = Object.values(a).filter(b);
  console.log(data)
}

pickBy({a:1, b:2, c:3, d:4}, ((prop, key) => prop >= 3))

Current Result: [3,4]

Expected Result: [{c:3}, {d:4}]

>Solution :

You could get the entries, filter by handing over the right format for filtering function and build objects of filtered entries.

const
    pickBy = (object, filterFn) => Object
        .entries(object)
        .filter(([k, v]) => filterFn(v, k))
        .map(([k, v]) => ({ [k]: v }));

console.log(pickBy({ a: 1, b: 2, c: 3, d: 4 }, (prop, key) => prop >= 3));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading