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.

1

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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)

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.