-4

I am very new to angular and I am assigned to a task where I want to get data from an API and iterate and display it in a chart. My angular version is 6.

This is the response JSON format, It is a list of objects-

[
    {
        "counts": 0,
        "time": "00:00:00"
    },
    {
        "counts": 0,
        "time": "01:00:00"
    },
    {
        "time": "02:00:00",
        "counts": 1
    },
    {
        "counts": 7,
        "time": "03:00:00"
    }
]

To fetch that

 data : [];

this.service.getPaymentDistributionData()
    .subscribe((res) => {
      console.log(res)
    })

How can I get each count and time and print?

Thanks,

2
  • 1
    Does this answer your question? Iterate over array of objects in Typescript Commented Aug 31, 2021 at 9:49
  • If i use of it is saying like Type 'Object' is not an array type or a string type Commented Aug 31, 2021 at 10:22

2 Answers 2

2
this.service.getPaymentDistributionData()
.subscribe((res) => {
    res.forEach(x => console.log(x.count))
})

Try Something Like this For Array of Object where res = [{}, {}]

for Object where res = {}

Object.keys(res).forEach((key) => )
Sign up to request clarification or add additional context in comments.

6 Comments

Same problem i am having here like Property 'forEach' does not exist on type 'Object'.
okay it should work perfectly on array of object i think you should check you data again if its only Object or Array Of objects.
Its array of objects
Please see i have noted in the question of my return type
I got your answer and i slightly modify it as res: any[], then it worked
|
1

You can use for .. of

for (let ct of res) {
     console.log(ct.counts);
     console.log(ct.time); 
}

2 Comments

here I am getting an error like Type 'Object' is not an array type or a string type. What is that.
Your service probably returns an Object, not an Array.

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.