Attempting to calculate the total for every individual item

Struggling to make sense of this JSON output, it feels like I'm stuck in a loop. The JSON data looks like this:

[
      {
"gosuResponse" : {
"tokenId" : "60e2d532-3d1c-4a95-adbd-aa352984c125",
"page" : 1,
"pageSize" : 1000,
"nbLinesTotal" : 15,
"serials" : {
  "serial" : [ "272072207980" ]
},
"data" : {
  "row" : [ {
    "col" : [ "2015-02-10", "", "1"]
  }, {
    "col" : [ "2015-02-10", "BNP-Blogs", "1504"]
  }, {
    "col" : [ "2015-02-10", "BNP", "66"]
  }, {
    "col" : [ "2015-02-10", "GOOMPlayer-Site", "6"]
  }, {
    "col" : [ "2015-02-10", "podcast", "19"]
  }, {
    "col" : [ "2015-02-10", "stream", "10"]
  }, {
    "col" : [ "2015-02-09", "", "6"]
  }, {
    "col" : [ "2015-02-09", "BNP-Blogs", "1742"]
  }, {
    "col" : [ "2015-02-09", "BNP", "61"]
  }, {
    "col" : [ "2015-02-09", "GOOMPlayer-Site", "2"]
  }, {
    "col" : [ "2015-02-09", "podcast", "18"]
  }, {
    "col" : [ "2015-02-09", "stream", "8"]
  }, {
    "col" : [ "2015-02-08", "", "7"]      
  }, {
    "col" : [ "2015-02-01", "stream", "8"]
  } ]
 }
}
}
]

To organize the similar names together, I used underscore.js library.

var items = result[0].gosuResponse.data.row;

    var groups = _(items).groupBy(function(o) {
        return o.col[1];
    });
    console.log(groups);

After running this code, the output is displayed as follows:

Object 
 - BNP : Array[4]
   - 0 : Object
     - col : Array[3]
       0 : '2015-02-10"
       1 : 'BNP'
       2:  '66'
   - 1 : Object
     - col : Array[3]
       0 : '2015-02-10"
       1 : 'BNP'
       2:  '66'

I am specifically interested in summing up the number value at position 2 for each object in the array.

While I have tested this with one key on my Plunkr, I am curious if there's a way to achieve this for all objects in the array.

Check out my Plunkr example here.

Answer №1

There seems to be no necessity for grouping items in this scenario:

var sum = {};
_.each(items, function(row) {
  var col = row.col;
  if (sum.hasOwnProperty(col[1])) {
    sum[col[1]] += parseInt(col[2]) || 0;
  } else {
    sum[col[1]] = parseInt(col[2] || 0);
  }
});

However, I must mention that my familiarity with underscore.js is limited and I may not be aware of all its functionalities.

Update: I came across a built-in solution in underscore.js that utilizes grouping as well:

var groups = _(items).groupBy(function(o) {
    return o.col[1];
});

var sum2 = {};
_.each(groups, function(group, key) {
  sum2[key] = _.reduce(group, function(memo, item) {
    return memo + (parseInt(item.col[2]) || 0);
  }, 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

Is the jQuery PJAX plugin failing to function in your HTML website?

I've been trying to implement jQuery PJAX on my HTML website, but unfortunately, it's not functioning as expected. The issue I'm facing is that the content outside the designated container is getting refreshed along with the intended area. ...

Why does it appear that Angular is undefined in this straightforward Angular demonstration?

I'm completely new to AngularJS and I've encountered an issue. Yesterday, I ran a very simple AngularJS application that I downloaded from a tutorial and it worked perfectly. The application consists of 2 files: 1) index.htm: <!DOCTYPE htm ...

Exploring the option of eliminating the email field from the PHP redirect function and transforming it into a pop-up notification

I am currently utilizing the following code to send an email notification to my address whenever a new user signs up: <?php $errors = ''; $myemail = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0ded1ddd ...

Combining a range to create a nicely formatted string with the help of Arrays

I've got some information stored in Range("A1:B2") A1: 190-00-001-00 A2: 190-00-002-00 B1: 00 B2: 00 The end result I'm aiming for is a string format like this: (('190-00-001-00','00'),('190-00-002-00','00&apo ...

Tips for confirming schedule accuracy

Trying to determine if a specific time falls between two others is the task at hand. Allow me to illustrate: Presently, it's Thursday, and the time reads 11:39 PM. Establishment X operates from 12:00 AM to 11:59 PM on Thursdays (a regular occurrence ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

angular.js threw an error message saying it couldn't recognize the provider angular-seed

I recently embarked on a new project using angularjs with angular-seed, but I encountered difficulties when trying to implement directives. My objective is to create fields based on choices stored in the controller. However, I keep running into an error: ...

Grab the URL from React Router

I need assistance with writing a function that updates the current location to match the route of a clicked button. Currently, the code is returning the URL of the page where the button was clicked, not the path related to the button itself. Are there an ...

React Js: Data not being properly updated in the application state

Presenting App.js - import './App.css'; import { connect } from 'react-redux' import { ActionChangeName } from "./Actions/Action"; function App(props) { return ( <div className="App"> <div> ...

Tips for manipulating 2 arrays where the value in one array is reliant on the value in another array

Currently, I have two arrays - arrayGuest and arrayRent. They both contain objects with a common field, GuestID. My goal is to create a list that combines fields from both arrays when their guestIDs match. The structure of the objects is as follows: class ...

Protractor Error: Identifier Unexpectedly Not Found

I've encountered a slight issue with importing and exporting files while working on Protractor tests. HomePage.js export default class HomePage { constructor() { this.path = 'http://automationpractice.com/index.php'; this.searchQ ...

Retrieving and showcasing XML data in JavaScript

I have a string that has been parsed from an XML page: var data = '<Message>Fermata 1431 - Linea 202 -> 08:57 Linea 201 -> 09:02 Linea 256B -> 09:02 Linea 202 -> 09:05 Linea R2 -> 09:06 Linea 201 -> 09:13 Linea 201 -> 09:18 ...

Having trouble getting the .push() method in JavaScript to function correctly

I've encountered an issue while trying to develop a function that iterates through each item in an array and records the index of a specific item when found. In this particular function, whenever the item 'contraband' is detected during the ...

Improving the adaptive design of a breadcrumb navigation trail

.breadcrumb input[type="radio"] { display: none; } .breadcrumb input[type="checkbox"] { display: none; } .question-header input[type="radio"] { display: none; } .panel-body input[type="radio"]~label { cursor: pointer; width: 100%; text-align ...

Guide to accessing and utilizing environment-specific values during configuration stage

My goal is to deploy my web application across multiple environments. With Continuous Integration, I can automate the generation of a config.json file for each specific environment. This file will include important URLs that need to be used. { "baseUrl" ...

JavaScript still mentions a class that no longer exists

One of my elements has a class of .collapsed. When this element is clicked, a jQuery function is triggered to remove the .collapsed class and add the .expanded class instead. Even after the .collapsed class is removed, the function I have created continue ...

React doesn't properly display JSON data

I am facing an issue with the code below that is supposed to display data from a JSON file. Instead of showing the desired data, it only displays the h1 with curly braces. Here is the faulty code: import prod from "../../data/produtos.json"; exp ...

rediscovering values following verification

When handling incoming requests matching /user/read/:user_id, I utilize "router.get" In "router.param", a new object named "user" is defined with attributes like name and age Later on in the code within "router.get", the user object is retrieved using ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...