How can the total sum of values from a list of JSON objects be calculated in an HTML document?

I am currently designing an HTML form that, upon submission of a user's name, should return an integer representing the sum of all purchased items by the user. The API response is in JSON format and appears as follows:

[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]

Below is my current HTML code:

   <!DOCTYPE html>
  <html lang="en">
   <head>
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="stylesheet" type="text/css" href="MyMain.css">
       <script language="JavaScript">
        function myFunction() {
            document.getElementById('myshow').innerHTML = 
                        document.getElementById("Name").value;

             return false;
          }
       </script>
   </head>
   <body>
      <div class="container">
            <div>
              <fieldset>
                <form method="POST" action="" onSubmit="return myFunction();">
                  <div class="row">
                    <div form-group">
                      <label for="fname">Your Name: </label>
                      <input type="text" class="form-control" name="name" id="Name" placeholder="Jon" value="">
                    </div>
                    </div>
                    <div>
                      <input type="submit" class="button" value="Submit"><br/>
                    </div>
                  </div>

                </form>

              </fieldset>
            </div>
      </div>
      <div class="container">
      <fieldset>
        <div>
            <label>Prices: </label>
            <p><span id='myshow'></span></p>
        </div>
      </fieldset>
     </div>
   </body>
</html>

I am unsure how to retrieve the API response and calculate the sum of item values.

Answer №1

The concise response to your query is as follows:

const data = '[{"Phone":800}, {"laptop":1500}, {"car":12000},{"watch":300}]';

// Convert the JSON string to a JavaScript object if the JSON is in string format
const parsedData = JSON.parse(data); 

let totalSum = 0;
Object.values(parsedData).forEach(function(item){
   totalSum += Object.values(item)[0]; // Calculate the sum of each object's value.
});

console.log(totalSum);

Answer №2

Implement the reduce() function in JavaScript.

const items = [{"apple": 3}, {"orange": 2}, {"banana": 5}, {"grapes": 4}];

let totalItems = items.reduce((accumulator, currentValue) => {
    return accumulator + currentValue[Object.keys(currentValue)[0]];
}, 0);

console.log(totalItems);

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

Trouble with useEffect not triggering in NextJS 13.4 (app router) application

When trying to fetch data from the next API route, I encountered an issue where the useEffect method did not trigger on page reload. Additionally, I was unable to make this component async as Next.js does not allow async functions in client components. pa ...

Unlocking the power of promises: How Node.js excels at handling

I'm facing a situation where my controller code is structured like this. const Users = require("../models/users"); class UserController() { getUserById(req, res) { const id = req.params.id; const users = new Users(); ...

Utilizing the real module instead of resorting to mock usage

I've configured Jest as follows: jest: { configure: { testEnvironment: 'jsdom', preset: 'ts-jest', transform: {...}, moduleNameMapper: { antd: '<rootDir>/__mocks__/antd/index.tsx&apo ...

Troubleshooting Issue with Custom WordPress Post Type and Function Not Showing Images or Post Information

Having trouble getting attachments from this particular post type to display within the function below. Instead of the URLs being set, blank boxes are showing up. I've been trying to make this function appear on the homepage, but I keep facing the sam ...

How can JavaScript be used to modify the locale of a web browser?

Is it possible to programmatically set the window.navigator.language using AngularJS? I am exploring different methods to achieve this. At the moment, I rely on a localization service to handle my i18n localization switching. ...

"HTML and JavaScript: The search functionality fails when trying to search for a string that is sourced from an array

Could someone assist me with a comparison issue I'm encountering? I am trying to use the includes() method to compare a list in a table with a list of names stored in a string. Strangely, when I hardcode the string directly into the includes() method, ...

Send multiple form submissions using JQuery Ajax without needing to refresh the page

I am facing an issue with my form submission using Ajax. After receiving a response in the form of another form, when I try to submit it again using the submit button, it doesn't go through Ajax and uses the normal method instead. Why is this happenin ...

Prevent selection duplication in adjacent select by disabling the option in AngularJS ng-options

In my table, I have 2 select options that change dynamically. <tr> <th>Start time</th> <th>End time</th> </tr> <tr ng-repeat="s in config.time"> <td> <select ng-model="s.start_time" ...

"Perfectly Centered: Aligning Vertically and Hor

My goal is to center a box vertically and horizontally, but I'm struggling to get it just right: HTML: <div id="wrapper"> <header> <div id="logoWrapper"> <div class="logo">Logo Here </di ...

I am having trouble with Fullcalendar not loading my JSON data to display events

I've been experimenting with the fullcalendar JavaScript library, but I'm struggling to load data from my MySQL database onto the calendar. When I test my db-connect.php file, it does return the first entry in the table, yet the calendar remains ...

Creating a sequence of isometric foes in the right arrangement or tackling the task of handling the stained rectangle?

Can someone lend a hand in fixing my Z-index order? I've been staring at this code for hours and my eyes are starting to cross. Maybe leaving a question on Stack Overflow overnight will steer me in the right direction. I've been tinkering with h ...

"message": "Please provide a valid user path.",

When attempting to store the user in the database, the response indicates that the "user" path is required even though the user value is present in req.body and logged for verification purposes. However, the issue persists with storing it in the database. ...

Accomplishing Nested Element Retrieval in Javascript

While this question may have been asked previously, it hasn't been tackled quite like this before... I have the following block of HTML code. <table class="fr ralign cartSummaryTable"> <tr> <td width="320px"> <div cl ...

Show results from selecting multiple dropdown options

I am looking to create a search function that displays results based on multiple dropdown selections. I have 4 dropdown menus and a submit button, but I am unsure how to show the search results upon clicking the submit button. The desired outcome is to dis ...

Targeting props within a Class Component: A Step-by-Step Guide

I am currently working on a MultiStep Form project. On the final page of the form, my goal is to push all the collected data to Firebase. I have been utilizing props and states to pass values from one page to another. However, I'm facing an issue in t ...

Issue arises when trying to insert an image avatar onto a globe in three.js

I have successfully implemented a rotating 3D globe using three.js with the code provided below. HTML <canvas id="canvas"></canvas> JS let camera; let renderer; function main() { const canvas = document.querySelector('#ca ...

Incorporate child routes within a React component

I've been attempting to include <route> in a component within a routers component, but it doesn't seem to be working. Can anyone provide some assistance? My login page currently has a form and I'd like to switch that out with routes. ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

Troubleshooting Tailwind CSS - Issues with Styles not Taking Effect

I've encountered a problem with my project that combines Tailwind CSS and Next.JS. Specifically, I'm facing an issue where certain Tailwind classes are not being applied correctly. For example, when I try to use the bottom-0 class, it doesn' ...

Using JQuery to properly introduce a script in the body of a webpage

<script> /* adjust #splash-bg height based on #meat element */ $(window).on('load',function(){ var splashbgHeight = $("#meat").css("top"); $("#splash-bg").css("height",splashbgHeight); $(w ...