0

I would like to filter the object based on values in a key value pair.

I want the keys which are only true.

Tried using array.filter but I am not able to find a solution.

Eg:-

const arry = [{'fname': true}, {'lname': true}, {'country': false}];

Can someone help me how to extract keys which have the values as true.

Expected o/p

['fname','lname'] as they are the only values which are true.

Community
  • 1
  • 1
  • Possible duplicate of [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Heretic Monkey Sep 10 '19 at 20:02

2 Answers2

1

You could reduce the array, take the entry of the first entries and check the value. Push the key, if the value is truthy.

var array = [{ fname: true }, { lname: true }, { country: false }],
    keys = array.reduce((r, o) => {
        var [key, value] = Object.entries(o)[0];
        if (value) r.push(key);
        return r;
    }, []);

console.log(keys);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Array.filter takes a function which should return true or false, which indicates whether a particular element from an array should be retained or not.

You have an array objects, and objects themselves can have multiple keys and values. You need a multi-step process here:

  1. Reduce your array objects into a single object (this might be a problem if multiple objects contain the same keys!)
  2. Select the keys out of your combined object with a value of true.

You can use Object.assign to merge objects. We'll use Array.reduce to reduce the array of objects into a single object:

const combined = arry.reduce((acc, val) => Object.assign({}, acc, val))

This will result in a single object containing all your key-value pairs:

// { country: false, fname: true, lname: true}

Now we just need to select the entries which have a true value, which results in an array of arrays:

const entries = Object.entries(combined).filter(([k, v]) => v)
// [["lname", true], ["fname", true]]

Then we can map out the keys from that array, like so:

entries.map(([k, v]) => k)
// ["lname", "fname"]

These steps could all be chained together for brevity.

const arry = [{'fname': true}, {'lname': true}, {'country': false}];

 Object.entries(arry.reduce((acc, val) => Object.assign({}, acc, val)))
   .filter(([k, v]) => v)
   .map(([k, v]) => k)
Chris Heald
  • 61,439
  • 10
  • 123
  • 137