Iterate over the JSON data structure and provide a concise summary of the outcome

I am facing an issue with calculating a JSON object and returning the average result.

Here is the JSON object in question:

var testJson = [{
                "1": "0.038728952407837",
                "2": "0.034420967102051",
                "3": "0.034113883972168",
                "4": "0.033237934112549",
                "5": "0.033545017242432",
                "6": "0.033923149108887",
                "7": "0.033990859985352",
                "8": "0.033454895019531",
                "9": "0.033518075942993",
                "10": "0.033759117126465",
                "11": "0.033965826034546",
                "12": "0.03358006477356",
                "13": "0.033926010131836",
                "14": "0.033300876617432",
                "15": "0.033140897750854",
                "16": "0.033447027206421",
                "17": "0.033830165863037",
                "18": "0.033417940139771",
                "19": "0.033578157424927",
                "20": "0.032893180847168",
            }]

Below is the code snippet I have been using:

var arr = testJson[0];
var total = 0;
for (var i = 0; i < arr.length; i++) {  
    total += arr[i];  
}
console.log(total)

The output of this code gives me a concatenated string rather than the expected result.

0.0387289524078370.0344209671020510.0341138839721680.0332379341125490.0335450172424320.0339231491088870.0339908599853520.0334548950195310.0335180759429930.0337591171264650.0339658260345460.033580064773560.0339260101318360.0333008766174320.0331408977508540.0334470272064210.0338301658630370.0334179401397710.0335781574249270.0328931808471680.0339531898498540.0339729785919190.0338070392608640.0332689285278320.0333919525146480.033372879028320.0353031158447270.0355949401855470.0359919071197510.036854982376099

I need help in identifying where I am going wrong in my approach.

Answer №1

To solve the issue, you need to address the type conversion problem in your code. The values in your testJson variable are currently stored as strings. When you use string1 + string2, it combines these strings into a new string. To perform mathematical operations, you should convert these string values to Float using the parseFloat function.

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

var arr = Object.values(testJson[0]);
var total = 0;
for (var i = 0; i < arr.length; i++) {  //iterate through the array
    total += parseFloat(arr[i]);  //perform the calculation
}
console.log(total)

Alternate Solution:

if(!Object.values)Object.values=obj=>Object.keys(obj).map(key=>parseFloat(obj[key]))
var total = 0;
Object.values(testJson[0]).forEach(function(val){total += val});

The code line I included,

if(!Object.values)Object.values=obj=>Object.keys(obj).map(key=>parseFloat(obj[key]))

serves as a polyfill.

According to Wikipedia; A polyfill in web development is a piece of code that enables a feature on browsers that don't support it natively. It usually refers to a JavaScript library that implements an HTML5 standard on older browsers or a proposed standard on current browsers. Essentially, "a polyfill acts as a substitute for a browser API".[1]

Answer №2

To ensure accurate calculation, convert the type to float before performing addition on JSON variables which are stored as strings. When adding strings without converting them to numbers, it results in concatenation. Use the following code snippet for conversion: total += parseFloat(arr[i]);

for (var key in arr) {
       if (arr.hasOwnProperty(key)) {
         total += parseFloat(arr[key]);
       }
     }
     console.log(total);

Answer №3

let sum = 0;
let data = [{
            "1": "0.038728952407837",
            "2": "0.034420967102051",
            "3": "0.034113883972168",
            "4": "0.033237934112549",
            "5": "0.033545017242432",
            "6": "0.033923149108887",
            "7": "0.033990859985352",
            "8": "0.033454895019531",
            "9": "0.033518075942993",
            "10": "0.033759117126465",
            "11": "0.033965826034546",
            "12": "0.03358006477356",
            "13": "0.033926010131836",
            "14": "0.033300876617432",
            "15": "0.033140897750854",
            "16": "0.033447027206421",
            "17": "0.033830165863037",
            "18": "0.033417940139771",
            "19": "0.033578157424927",
            "20": "0.032893180847168",
        }]
(data || []).forEach(function(obj){
    for(let key in obj ){
       sum += parseFloat(obj[key], 10);
    }
});

Answer №4

Utilize the parseFloat method.

let jsonData = sampleData[0];
let sum = 0;
for (let j = 0; j < jsonData.length; j++) {  //iterate through the data
    **sum += parseFloat(jsonData[j]);  //Perform calculation!**
}
console.log(sum)

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

Having trouble with the installation of js-bson

While attempting to install bson as a dependency of mongodb on my Windows 7 64bit system, I encountered the following error: npm WARN package.json <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97c0f8f4fff2f9e7fbf6f9f2e5d7a7b9 ...

Encountering an issue while trying to initiate a fresh React Native Project

As I work through the setup steps outlined in the React Native Documentation on my M1 MacBook Pro, I encounter a stumbling block. Despite successfully running React projects and Expo projects on this machine before, I hit a snag when trying to create a new ...

Failure of $.post to activate the function

I'm really struggling to understand why the alert or console.log functions are not being triggered in this snippet of code: $.post("http://localhost:8080/mail", jsonObject, function(data) { ...

Deleting a row from a table in AngularJS can be accomplished by following these steps

I am having trouble with deleting rows from a table using angularjs. When I try to delete a row, it ends up deleting the previous row instead of the correct one. How can I fix this issue? Please check out the working DEMO Here is the code snippet: < ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

What is the best way to change a double-quoted integer into an integer?

Can anyone help me convert this to an integer? "'10'" Appreciate any assistance. ...

The JavaScript Table Project: Array Functionality and Looping - Glitch Detected

Need help fixing an issue with a broken table that uses both 1 and 2 Dimensional Arrays along with for-loops. Is there a way to ensure that "loanAmount[row]" is displayed only once in the leftmost column of the table? function print2DArrayTable(this2DArr ...

Linking Angular Template: Connect the height of one container to the height of another

My objective is to dynamically bind the height of an angular component to a div element. I am experimenting with using template reference to access the height. Is there a way to achieve this in a clean manner? I would like to implement it similar to the c ...

HTML list with clickable elements for querying the database and displaying the results in a <div> element

Patience please; I am a newcomer to StackOverflow and this is my inaugural question. Struggling with writing an effective algorithm, I wonder if my attempts to "push" it forward are causing me to complicate what should be a straightforward concept, or if i ...

Trigger a JQuery dialog after submitting a form in MVC and pause execution until a user responds

I'm working on an MVC app that has a form. When the user clicks the 'Save' button, it should submit the form to the controller and save the changes. If certain conditions are met, a JQuery UI dialog will pop up, prompting the user for input ...

How can we generate three planes in geometric space that are perpendicular to the x, y, and z

I have been tasked with creating three plane geometries in a scene, one perpendicular to the x-axis, one perpendicular to the y-axis, and one perpendicular to the z-axis. The desired result should somewhat resemble this image: https://i.sstatic.net/L1K6G.p ...

Strategies for delaying the loading of CSS when importing

import 'react-dates/lib/css/_datepicker.css' The CSS mentioned can be deferred since it is not critical. Is it possible to defer the loading of CSS when utilizing import? I found information on deferring CSS loading using <link> from Goo ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

The Formik fields are persistently showing validation errors even though they are filled in correctly. To view the issue, you can check out the code in the codesandbox link provided

const updateCreateFormField = (e) => { const { name, value } = e.target; setCreatForm({ ...createForm, [name]: value, }) console.log({ name, value }); }; //The onChange variable in the fields is updated on the above ...

unleashing the magic of AJAX: a guide to extracting

In my Symfony project, I am attempting to retrieve the content of an AJAX request in order to check the data using dump(). The purpose is to process this data and perform a SQL query. However, when I use dump() in my controller, there doesn't appear t ...

MongoDB does not recognize the PropertyName specified in the JsonPropertyAttribute

In my ASP.NET Core application using .NET 8, I have a data model with property names defined using the JsonProperty(PropertyName = "xxx") attributes. Here is an example: [JsonProperty(PropertyName = "enable_cancel_login")] public bool E ...

Cannon-js: Experience dynamic body bouncing on the y axis as it reacts to force applied on the x and z axes

Currently, I am working on an FPS game where the player controller applies force based on keyboard inputs to a dynamic cannon body. The angular dampening is set to 1 on the player body. The PlayerController class takes both the player class (which extends ...

Error: JSON parsing error due to attempting to access list indices with a string instead of an integer or slice

My goal is to retrieve and print at least one key value from the JSON that is returned. I'm following this basic tutorial for guidance. response=None booking_source = 'sourceBusinessName' api_request ='http://api.com' r = requ ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

The popup.html file was overlooked during the generation of the Chrome extension build with Vite

I'm currently utilizing a github CLI plugin found at this link to set up mv3 chrome extensions using vue and vite. The initial template is properly set up and I can work on it without any issues. However, I encounter a problem when trying to utilize ...