Am trying to find the count of isSelected= true form the given object.
{
"MainData1": [
{
"Child1": [
{
"value": "item1",
"isSelected": true
},
{
"value": "item2",
"isSelected": true
}
]
}
],
"MainData2": [
{
"Child2": [
{
"value": "item",
"isSelected": true
}
]
}
]
}
i Was tried forEach loop.
can we do it in a simple way?
The expected count will be 3
Note: It is a dynamic data
Thanks in advance
CodePudding user response:
For all the unknown keys you can use Object.values()
to retrieve corresponding values and then use flatMap
and filter to get count for each object. Outer array.reduce()
can be used to count all nested filtered arrays:
const data = {
"MainData1": [
{
"Child1": [
{
"value": "item1",
"isSelected": true
},
{
"value": "item2",
"isSelected": true
}
]
}
],
"MainData2": [
{
"Child2": [
{
"value": "item",
"isSelected": true
}
]
}
]
};
const count = Object.values(data).flatMap(x => x).reduce(
(count, current) => count Object.values(current).flatMap(x => x).filter(x => x.isSelected).length, 0);
console.log(count);
CodePudding user response:
I think the line of code, should being like this
const data = {
"MianData": [
{
"Child1": [
{
"value": "item1",
"isSelected": true
},
{
"value": "item2",
"isSelected": true
}
],
"Child2": [
{
"value": "item3",
"isSelected": true
},
{
"value": "item4",
"isSelected": false
}
]
}
]
}
let result = 0;
if (data.MianData.Child1[0].isSelected){
result ;
}
if (data.MianData.Child1[1].isSelected){
result ;
}
if (data.MianData.Child2[0].isSelected){
result ;
}
if (data.MianData.Child2[1].isSelected){
result ;
}
console.log(result);
//or
return result;
Hope it should be helpful for you.
Thank you