I am trying to figure out a way to filter an object to get only the attributes of a certain type.
My object looks like this :
analysis: {
cultural1: true,
cultural2: false,
cultural3: true,
cultural4: true,
culturalScore: 75,
environment1: true,
environment2: true,
environment3: true,
environment4: true,
environmentScore: 100,
createdAt: "2021-09-15 11:43:58 -0400",
id: 543,
review: 'Lorem ipsum odor'
}
What I want is to get an array of only the boolean attributes of that object. Thank you!
CodePudding user response:
- Using
Object#keys
, get the list of attributes - Using
Array#filter
, iterate over the above list and return keys with boolean values usingtypeof
const analysis = {
cultural1: true,
cultural2: false,
cultural3: true,
cultural4: true,
culturalScore: 75,
environment1: true,
environment2: true,
environment3: true,
environment4: true,
environmentScore: 100,
createdAt: "2021-09-15 11:43:58 -0400",
id: 543,
review: 'Lorem ipsum odor'
};
const keysWithBooleanValues =
Object.keys(analysis)
.filter(k => typeof analysis[k] == "boolean");
console.log(keysWithBooleanValues);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
use Object.entries
to get an array of key,values
pair and then filter those values based on their types using typeof
.
let analysis = {
cultural1: true,
cultural2: false,
cultural3: true,
cultural4: true,
culturalScore: 75,
environment1: true,
environment2: true,
environment3: true,
environment4: true,
environmentScore: 100,
createdAt: "2021-09-15 11:43:58 -0400",
id: 543,
review: 'Lorem ipsum odor'
}
let result_obj = Object.fromEntries(Object.entries(analysis)
.filter(([k,v]) => typeof(v) === 'boolean'))
console.log(result_obj)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>