Loop through the JSON response and calculate the total bill using TypeScript

Having trouble calculating the total sum of bills in an order list using typescript. The error message 'Object is of type 'unknown' keeps popping up when trying to access the total bill field. Interestingly, it works fine in the browser console but throws an error in Visual Studio Code.

Below is the JSON response:

{
    "order_list": {
       
            "32212000000037": {
                "invoice_id": "32212000000037",
                "customer_id": "006019000015",
                "customer_name": "Spantik",
                "inv_date": "2020-12-24",
                "prod_date": "2020-12-24",
                "inv_time": "09:00",
                "total_bill": 22,
                "notification": "waiting",
                "sales_id": "",
                "inv_type": "regular",
                "danger": "over"
            },
            "32212000000036": {
                "invoice_id": "32212000000036",
                "customer_id": "006019000015",
                "customer_name": "Spantik",
                "inv_date": "2020-12-24",
                "prod_date": "2020-12-24",
                "inv_time": "14:57",
                "total_bill": 22,
                "notification": "waiting",
                "sales_id": "",
                "inv_type": "regular",
                "danger": "over"
            }        
    }
}

Here's my attempt at solving the issue:

countTotalBill(orderDate: string) {
  let totalBill = 0;

  const itemList = this.orderLists[orderDate];

  if (itemList != null) {
    const arr = Object.values(itemList);

    arr.filter(ele => {
      totalBill = totalBill + ele.total_bill; // <<<<<<======= here is the problem
    });
  }

  return totalBill;
}

Answer №1

Instead of using filter, opt for reduce function,

totalBill = arr.reduce((acc,cur)=>acc + cur.total_bill,0)

If you prefer Types:

const apiResp = {
    order_list: {
        "32212000000037": {
            invoice_id: "32212000000037",
            customer_id: "006019000015",
            customer_name: "Spantik",
            inv_date: "2020-12-24",
            prod_date: "2020-12-24",
            inv_time: "09:00",
            total_bill: 22,
            notification: "waiting",
            sales_id: "",
            inv_type: "regular",
            danger: "over",
        }
    },
};

interface OrderItem {
    [key:string]:string|number;
    total_bill: number;
}

const arr:OrderItem[] = Object.keys(apiResp).map(x=>apiResp[x])

console.log(arr.reduce((acc,cur)=>acc + cur.total_bill,0))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Troubleshooting problem with jQuery's .has() and .click() functions

I have created a lengthy html code: <div id="el"> <p data-skip>Blablabla</p> // On click, toggle this, and toggle next p <p data-skip>Blablabla</p> // On click, toggle this, and toggle next p <p data-skip>Bl ...

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

Unable to allocate a second item to an existing one

Encountering an unusual issue while trying to assign an item a second time. Initial scenario: I am working with a jqxTree containing various items as shown below: - apple - oracle - microsoft When I drag and drop one item into another, the structure loo ...

The ngx-image-cropper in Angular only necessitates a button click, making the default cropper unnecessary

Currently, the image is cropped by default when loaded, but I would like the crop to only occur when the crop button is clicked. I tried searching on Google and found autoCrop:false, but I am unsure where to place it in the code. Below is the HTML code: ...

Struggling to delete elements from observable array within Knockoutjs framework

I am attempting to use knockoutjs to remove a user from an observable array called users. It seems like my viewModel may not be working correctly because it is within a document.ready function. Here is some context about the code below: My application fet ...

Tips for manipulating rows in HTML using jQuery when the id attribute is added

Apologies in advance for any language errors in my explanation I am working on an input table where each row has a unique ID, and the input in each row affects the next row. As new rows are added, I have implemented an incremental numbering system for the ...

Sorting through a table based on the name of the element

I am currently working on filtering an HTML table using a search form. It's working great, but I'm facing an issue where the filtered elements are trying to fill the entire width of the table instead of maintaining their original width (which is ...

Transmitting information from a modal component to its parent component in Angular using MDB

I encountered an issue with my CRUD application where uploaded files do not immediately appear on the page until I refresh it. The same problem occurs when trying to delete a file. For deleting, I was able to fix it by subscribing to the onClose event on ...

Ways to incorporate a while loop into a randomizing function

I've been diving into JavaScript and managed to create a website that displays random gifs when clicked from an array. Now, my goal is to implement a while loop to prevent duplicate images from being shown consecutively. However, I seem to be facing ...

The YouTube video continues to play even after the container is closed

I recently worked on implementing a lightbox feature using jQuery, where a window opens upon clicking an element. Everything was working fine with images, but when I tried to open a YouTube video and play it, the video kept playing in the background even a ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...

Tips for displaying an error message when there is no match found in ng repeat due to filtering

I'm facing an issue with displaying an error message when no match is found after searching in a text box. I've used ng-show to display the message, but it's not working as expected. Can someone assist me with this problem? I am relatively n ...

Exploring the power of utilizing multiple classes with conditions in Angular 2+

Can you help me figure out how to use a condition for selecting multiple classes with [ngClass] in Angular? <td> <span [ngClass]="{ 'badge badge-success': server.type === 'PRODUCTION', 'ba ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Creating an element that remains fixed once it reaches a distance of 50px from the top of the screen

Hey there! I'm working with an html div element that currently scrolls along with the page, but I was wondering how I can make it become fixed once it reaches a distance of 50px from the top of the screen. Any ideas on how to achieve this? Just to pro ...

Error: Unable to convert value to a string in Mongoose Schema

Hey everyone, I'm facing an issue while trying to send an array of strings with Mongoose Schema. It works fine for the tags but not for the selectedFile... Mongoose Schema: import mongoose from "mongoose"; const postSchema = mongoose.Schem ...

You are unable to declare objects within an object of a Class in JavaScript

class B{ item = {}; item.name = "example"; } let b = new B() What is the reason behind not being able to define an object and add a property inside a class like this? ...

Top method for handling chained ajax requests with jQuery

I'm facing a scenario where I have to make 5 ajax calls. The second call should only be made once the first call returns a response, the third call after the second completes, and so on for the fourth and fifth calls. There are two approaches that I ...

Display the component only if the image source is legitimate

Before rendering an Image component, I want to ensure that the URL is valid and not broken. My current approach seems error-free and the onload function is functioning properly. However, I suspect there might be an issue with how I am handling the return ...