Guide on obtaining the total value from a JSON Array in Angular 2 using TypeScript

I received a JSON response which includes carts values with different amounts.

"carts": {
            "value": [
                {

                    "Amt": 40

                },
                {
                    "Amt": 20.25

                },
                {

                    "Amt": 10.30

                }

            ]
        }

My goal is to calculate the sum of all Amt values, which should be 70.55. I am learning TypeScript and would appreciate any help on how to achieve this task.

Answer №1

For efficient utilization of JavaScript's reduce function (also applicable to TypeScript), follow this structured approach:

const data = {
  "list": {
    "elements": [
      {
        "value": 30
      },
      {
        "value": 15.75
      },
      {
        "value": 7.90
      }
    ]
  }
};

const result = data.list.elements.reduce((total, item) => total + item.value, 0);

console.log(result);

Remember, for compatibility with IE8, it is imperative to integrate a polyfill (as detailed on the MDN documentation).

Answer №2

Although the Rxjs' Observable response is a popular choice, it's worth noting that there is an alternative approach using JavaScript arrays and the reduce function, which can also be utilized in Typescript.

// assuming that the variable 'carts' already contains the deserialized JSON
let total: number = carts.value.reduce( 
  (a: number, b) => a + b.Amt, 0);

Following @Stefan's feedback:

Certain mistakes have been corrected, and it is advisable not to assign a type to 'b', allowing for inference based on context and potentially catching any TypeScript errors during compile-time.

Answer №3

One way to achieve this is by employing observable reduce function. Suppose you are dealing with an Http response:

this.http.get('url')
    .map(response.items.total)
    .map(res => res.Price)
    .reduce((x, y) => x + y)
    .subscribe(total => console.log(total))

Answer №4

const total = 0;
    for (let j = 0; j < this.baskets.value.length; j++) {
        total += this.baskets.value[j].Amount;
    }

Answer №5

If you want to calculate the total cost of items in a shopping cart, you can create a function similar to this:

public calculateCartTotal(): number {
    let totalCost: number = 0;

    this.itemsInCart.forEach((item: any) => {
        totalCost += Number(item.price);
    });

    return totalCost;
}

Answer №6

This is the simple method to achieve the desired outcome.

  let total = 0;
  for(const item of json.carts.list){
      total += item.amount;
  }

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

Transforming JSON information for Google chart data table

I am currently working on converting JSON data into a suitable format for a Google Chart visualization: var jsonData = {"Battery Voltage, (A)": {"2017-11-11T00:00:00.000Z":12.3, "2017-11-11T00:01:00.000Z":12.35, ...

How to use the importrange function to calculate the frequency of a specific value in a column

Within this google sheet, there is text data located in range O3:O: https://docs.google.com/spreadsheets/d/1xNFVHLnQGkRgZdLmejCyU0BByOPBY8NMoIYj6SkTFGY/edit?usp=sharing The main goal here is to use Query + importrange to calculate how many times the value ...

Displaying JSON data using Vue.js

fetching JSON data save movieData: {} ...... retrieveMovieData (context, parameter) { axios.get(API.movieData + parameter.id) .then(response => { context.commit('MOVIE_DATA', response.data) }) .catch(error => ...

Is there a way to invoke a function within a mat-error element?

I need to display an error message in my input field! The function will return true if both passwords match, otherwise it will return false. How can I invoke a boolean function inside mat-error! My Function: checkPasswords(): Boolean { // 'passwords& ...

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

I am looking to present a nested array within an array in a tabular format

This is the structure of my database: [{ "firstName": "Shaun", "salary": [ { "id":1, "rate": 250, }, { "id":2, "rate": 290, } ] },{ "firstName": "Julian", "salary": [ { "id":1, "rate": 750, ...

Saving a revised JSON file using AngularJS

Currently, I am in the process of developing a phonegap application using AngularJS that relies on a .json file to store an array of entries. The main goal I am aiming for is to enable users to mark specific entries as favorites and then utilize that data ...

Can you explain the distinction between declaring type using the colon versus the as syntax?

Can you explain the variation between using the : syntax for declaring type let serverMessage: UServerMessage = message; and the as syntax? let serverMessage = message as UServerMessage; It appears that they yield identical outcomes in this particular ...

Why is it possible to assign a variable holding a char array to a pointer in C, but attempting to take the address of that same pointer is not allowed?

Let's examine the following code snippet: char stringy[] = "There's too much confusion, I can't get no relief!"; char *pStringy; pStringy = stringy; It's interesting how this code compiles without any errors. Although stringy ...

Having trouble injecting $resource into my Jasmine unit test

I've encountered an issue while trying to test my self-written service that utilizes $resource. I'm facing difficulties when trying to inject $resource into my test spec. My setup includes Typescript with AngularJS 1.6.x, and here is a snippet o ...

Encountering an error: "Unhandled promise rejection SyntaxError: Unexpected character in JSON data at line 1 column 1."

When the submit button is clicked, my registration form data is sent using an event function called postData() in React. The user data is sent at the register route, and I have mentioned line numbers in the comments: const postData = async(event) =>{ ...

Ways to Execute the Constructor or ngOnInit Multiple Times

Here's the scenario I'm facing: I have developed an app with multiple screens. One of these screens displays a list of articles. When a user clicks on an article, they are directed to another screen that shows the details of that specific item. ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

Exploring the Potential of Powershell, JSON, and Hashtables

Looking for Help [ { "example": "abc123", "exampleName": "abcd_test", "exampleShortcode": "", "isComplete": false }, { "example": "def456", ...

What is the best way to send anonymous lists to a calling method from a static method?

public JsonResult GetReport(string reportSelected, string firstDateGiven) { _context = new ReportDB(); var theResults = miPolicyTransactions.Select( x => ...

Discovering the parent key (along with its siblings) with the highest value of a specific key within an array using max_by function

After experimenting with the max_by function in jq, I discovered that two different commands resulted in different maximum values. #1. cat file | jq '[.tx[].vout[]] | max_by(.value)' #2. cat file | jq '[.tx[]] | max_by(.vout[].value)' ...

A glitch was encountered during the execution of the ionic-app-scripts subprocess

I recently started using Ionic 3 and created an application that I'm trying to convert into an APK. To generate a debug (or testing) android-debug.apk file, I used the following CLI command: ionic cordova build android --prod The pages are declared ...

Unable to modify a variable within a request

Having trouble updating a variable within a request? It seems like the variable doesn't change when it should. const request = require("request"); var all = JSON.parse(body); var steamplayer = all['response']['players']['play ...

Resolving route data in Angular 2 and above

When retrieving data from an API in an Angular route resolver, I encountered a problem where if there was an error due to a stale token, I needed to refresh the token and then retry the API call. Below is the code snippet illustrating this scenario: impor ...