Array.filter
is a method that takes a function as an argument, and this function should return either true or false based on whether a specific element from an array should be kept or not.
When dealing with arrays of objects, each object can have multiple keys and values. To process this, you can follow these steps:
- Combine all the objects into a single object (be cautious if there are similar keys in multiple objects).
- Select the keys from the combined object that have a value of true.
To merge objects, you can use Object.assign method. By utilizing Array.reduce, you can consolidate the array of objects into a singular object:
const combined = arry.reduce((acc, val) => Object.assign({}, acc, val))
Now, you will have a single object containing all the key-value pairs like this:
// { country: false, fname: true, lname: true}
Next, filter out the entries with a true value, resulting in an array of arrays:
const entries = Object.entries(combined).filter(([k, v]) => v)
// [["lname", true], ["fname", true]]
You can then map out the keys from that array as follows:
entries.map(([k, v]) => k)
// ["lname", "fname"]
All these steps can be chained together for a more concise solution.
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)