I need to get an array with specific key values of an object.
Assume there is this object (optional some more different keys)
{
username: 'bla',
admin: true,
editor: true,
user: false,
foo: 'bar'
}
I only need to process the keys admin, editor and user and get those keys in an array, if their value is true. So in the example the result should be:
['admin', 'editor']
If all three keys have a false value, it should return an empty array.
I would do a filter first:
obj.filter(e => ['admin', 'editor', 'user'].indexOf(e) > -1 && !!e)
and then extract the keys?
As you already have the list of fields, just apply a .filter call on that:
const obj = {
username: 'bla',
admin: true,
editor: true,
user: false,
foo: 'bar'
};
const fields = ['admin', 'editor', 'user'];
const result = fields.filter(field => obj[field] === true);
console.log(result);
You can get keys from object using Object.keys and apply filter for your require data. Try below code it should work for you.
const obj =
{
username: 'bla',
admin: true,
editor: true,
user: false,
foo: 'bar'
}
const objKeys = Object.keys(obj).filter(item => (obj[item] && typeof obj[item] == "boolean"));
get only keys:-
console.log(objKeys)
get array of object with key value:-
console.log(objKeys.map(item => ({[item] : obj[item]})))