Let my object have the following data:
{
mongoose: {
name: "Starky",
age: 3,
playful: false
},
dog: {
name: "Maks",
age: 7,
playful: false
},
parrot: {
name: "Petty",
age: 4,
playful: true
}
}
How can i count the number of booleans?
I know that I can use .reduce
, but I didn’t understand exactly how to use it correctly, in an attempt to use it, I just got undefined
.
CodePudding user response:
you can do something like this
to check if it is a boolean I have used !!
and ===
const countBoolean = data => Object
.entries(data)
.reduce((res, [k, v]) => {
return res Object.values(v).filter(value => value === !!value).length
}, 0)
const data = {
mongoose: {
name: "Starky",
age: 3,
playful: false
},
dog: {
name: "Maks",
age: 7,
playful: false
},
parrot: {
name: "Petty",
age: 4,
playful: true
}
}
console.log(countBoolean(data))
CodePudding user response:
Here,
var d = {
mongoose: {
name: "Starky",
age: 3,
playful: false
},
dog: {
name: "Maks",
age: 7,
playful: false
},
parrot: {
name: "Petty",
age: 4,
playful: true
}
}
console.log('Data',d) //Console for data
function cc(){ //Create function
let totalBool=0;
let totalTrue=0;
let totalFalse=0;
Object.keys(d).forEach((x)=>{
let dd = Object.keys(d[x]);
dd.forEach((y)=>{
if(typeof(d[x][y])=='boolean')
{totalBool }
if(d[x][y]==true)
{totalTrue }
if(d[x][y]==false)
{totalFalse }
})})
console.log('TotalBool :',totalBool);
console.log('TotalTrue :',totalTrue);
console.log('TotalFalse :',totalFalse);}
console.log(cc()) // Console for know bool value