0

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?

1
  • Do you want to collect all the values from all the arrays? Commented Sep 8, 2022 at 9:50

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

9 Comments

Hi, I have edited this object? I have tested your code, it does not work.
@user1938143 Could you share the object you are testing with, in the question? with this code?
Hi the error is: Property 'status' does not exist on type TestObject
@user1938143 Could you share the original angular code where the error occours, if possible a stackblitz. else you can put any type to the property and solve the issue!
the problem is, the object ist a type of TestObject.
|
0
let sum = 0;
for (const subobj in obj){
    sum += obj[subobj].status == "warning" ? 1 : 0;
}

Comments

0

You can do this with a forEach function on the array generated by the Javascript Object.values method.

let sum = 0;
Object.values(obj).forEach(value => {
    if(value.status == 'warning'){
        sum += 1;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.