I have a question about hot to get the number of a value in object with typescript. the object looks like this:
obj : TestObject = {
name: "test",
street: "test"
subobj1: {
status: warning,
time: 11
}
subobj2: {
status: oki,
time: 12
}
subobj3: {
status: warning,
time: 13
}
}
}
the TestObject is defined:
export interface TestObject {
name: string,
street: string,
subobj1: SubObj1,
subobj2: SubObj2
}
so I want to get the number of warning
I want to a method, which in this case returns 2 back.
how should the code look like?
CodePudding user response:
First convert the object to array of key and values using Object.entries
then use filter
for the condition, finally length of the values is the desired output!
let obj = {
name: "test",
street: "test",
subobj1: {
status: 'warning',
time: 11
},
subobj2: {
status: 'oki',
time: 12
},
subobj3: {
status: 'warning',
time: 13
},
}
console.log(Object.entries(obj).filter(([key, value]) => key.indexOf('subobj') > -1 ? value.status === 'warning' : false).length);
CodePudding user response:
let sum = 0;
for (const subobj in obj){
sum = obj[subobj].status == "warning" ? 1 : 0;
}
CodePudding user response:
let sum = 0;
Object.values(obj).forEach(value => {
if(value.status == 'warning'){
sum = 1;
}
});