How can i calculate the rating in the rating array and still return it as a response

Viewed 57

This is the sample JSON response from the Backend, the rating is in ratings array and the value is rating, so I want to calculate the average rating for each course and still return it as a response to frontend, I tried using Object.Assign() but is worked well when i am fetching just one course but when i am fetching all courses, it doesn't work.

please i need help

{
    "message": "Fetched successfully",
    "status": "Success",
    "statusCode": 200,
    "data": {
        "items": [
            {
                "id": 210,
                "courseUuid": "93b760a7-505e-41bf-b57e-d84ecf53255f",
                "userId": 2,
                "title": "Complete Angularzero to hero",
                "imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655654436946-f02118c8-e3e9-44e5-8913-48d4f45cd816.png",
                "slugUrl": "Complete-Angularzero-to-hero-19-06-2022-93b760a7-505e-41bf-b57e-d84ecf53255f",
                "amount": "50,600",
                "averageRating": "11.5",
                "createdAt": "2022-06-19T16:00:43.009Z",
                "updatedAt": "2022-06-19T23:27:46.073Z",
                "user": {
                    "id": 2,
                    "userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
                    "email": "jessika76@hotmail.com",
                    "nawisNumber": "NAWIS/2022/54682884"
                },
                "category": {
                    "id": 1,
                    "categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
                    "name": "Front-End Development",
                    "slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
                },
                "duration": {
                    "id": 23,
                    "durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
                    "duration": "5 Months"
                },
                "enrollments": [
                    {
                        "id": 1,
                        "paymentStatus": "Not Completed",
                        "createdAt": "2022-06-19T16:04:22.375Z",
                        "user": {
                            "id": 3,
                            "userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
                            "email": "damion.jacobs84@yahoo.com",
                            "nawisNumber": "NAWIS/2022/12758991"
                        }
                    },
                    {
                        "id": 2,
                        "paymentStatus": "Not Completed",
                        "createdAt": "2022-06-19T16:07:37.059Z",
                        "user": {
                            "id": 6,
                            "userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
                            "email": "olaf_bailey@hotmail.com",
                            "nawisNumber": "NAWIS/2022/11177867"
                        }
                    }
                ],
                "ratings": [
                    {
                        "id": 1,
                        "rating": 2,
                        "review": "some text here",
                        "createdAt": "2022-06-19T16:04:40.339Z",
                        "user": {
                            "id": 3,
                            "userUuid": "ad0b0ad4-368d-4f09-ae99-80d2bcaed3d6",
                            "email": "damion.jacobs84@yahoo.com"
                        }
                    },
                    {
                        "id": 2,
                        "rating": 5,
                        "review": "some text here",
                        "createdAt": "2022-06-19T16:07:23.798Z",
                        "user": {
                            "id": 6,
                            "userUuid": "cbfbc6a7-dfd7-4f74-a545-a1423ccdb0f3",
                            "email": "olaf_bailey@hotmail.com"
                        }
                    }
                ]
            },
            {
                "id": 208,
                "courseUuid": "16855bd6-dd18-420a-8611-bc77bbda818c",
                "userId": 2,
                "title": "Complete Vuejs zero to hero",
                "imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653347091-cfee6022-0d3a-43e2-b780-986eda2607ed.png",
                "slugUrl": "undefined-19-06-2022-16855bd6-dd18-420a-8611-bc77bbda818c",
                "amount": "0",
                "averageRating": "0",
                "createdAt": "2022-06-19T15:42:30.273Z",
                "updatedAt": "2022-06-19T15:53:07.726Z",
                "user": {
                    "id": 2,
                    "userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
                    "email": "jessika76@hotmail.com",
                    "nawisNumber": "NAWIS/2022/54682884"
                },
                "category": {
                    "id": 1,
                    "categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
                    "name": "Front-End Development",
                    "slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
                },
                "duration": {
                    "id": 23,
                    "durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
                    "duration": "5 Months"
                },
                "enrollments": [],
                "ratings": []
            },
            {
                "id": 207,
                "courseUuid": "bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
                "userId": 2,
                "title": "Complete Vuejs zero to hero",
                "imageUrl": "https://our-akademy-uploads.s3.eu-west-1.amazonaws.com/courses/1655653325613-dda17c5c-2a4a-435a-99cb-ad28ea01bbb0.png",
                "slugUrl": "Complete-Vuejs-zero-to-hero-19-06-2022-bdb3ee71-0c0b-41d8-9049-5fa6a2a230f3",
                "amount": "50,600",
                "averageRating": "0",
                "createdAt": "2022-06-19T15:42:12.687Z",
                "updatedAt": "2022-06-19T15:42:12.687Z",
                "user": {
                    "id": 2,
                    "userUuid": "b1f8def8-aa1d-4a57-b743-174a6ee738ec",
                    "email": "jessika76@hotmail.com",
                    "nawisNumber": "NAWIS/2022/54682884"
                },
                "category": {
                    "id": 1,
                    "categoryUuid": "3a4def94-dd1a-451c-8f84-476096203710",
                    "name": "Front-End Development",
                    "slugUrl": "Front-End-Development-18-06-2022-ec0a7634-b710-4723-b646-4cde33d3d15a"
                },
                "duration": {
                    "id": 23,
                    "durationUuid": "3500b0d0-8d98-46d6-80d8-6363c09e887c",
                    "duration": "5 Months"
                },
                "enrollments": [],
                "ratings": []
            }
        ],
        "meta": {
            "totalItems": 209,
            "itemCount": 3,
            "itemsPerPage": 6,
            "totalPages": 35,
            "currentPage": 1
        },
        "links": {
            "first": "http://ourakademy.com/api/v1/courses?limit=6",
            "previous": "",
            "next": "http://ourakademy.com/api/v1/courses?page=2&limit=6",
            "last": "http://ourakademy.com/api/v1/courses?page=35&limit=6"
        }
    }
}
2 Answers

Assuming you put your json response in sampleJson variable

let sampleJson  = YOUR JSON RESPONE  
let sum = 0
let noOfRatings = 0
if(sampleJson && sampleJson.data && sampleJson.data.items){
    sampleJson.data.items.forEach(item => {
        item.ratings.forEach(i => {
            if (i && i.rating) { sum += i.rating; noOfRatings++ }
        })
    });
    if(sum && noOfRatings){
        let averateRating = sum / noOfRatings
        console.log('Average Rating : ',averateRating)
    }
}

You will get average rating using this code. Hope it helps :)

This is how i fixed the problem

    const courses: any = await this.find();
    for (let i = 0; i < courses.length; i++) {
      const course = courses[i];
      const sum: any = course.ratings.reduce((accumulator, object) => {
        return accumulator + object.rating;
      }, 0);
      courses[i] = {
        ...course,
        avg: sum / course.ratings.length,
      };
    }
    return courses;
Related