Tips for calculating the total value of a nested array

I seem to be facing a slight logic issue at the moment.

Currently, I have an accordion with images taken

https://i.sstatic.net/UUs8Y.png

In the HTML, you'll find headers for LIVE BETTING, MLB, MLB Props, and NBA (which is just a snippet of a list containing almost 25 sports)

  <accordion>
    <accordion-group ng-repeat="sport in sports">
      <accordion-heading>
        <div ng-click="addSportToLines(sport);">
          <span>{{sport.name}}</span>
          <span class="badge">{{sport.leagues.length}}</span>
        </div>
      </accordion-heading>

      <div>
        <a ng-repeat="league in sport.leagues"
           ng-click="addLeagueToLines(league)">
           <span>{{league.name}}</span>
           <span class="badge">{{league.offeringsAvailable}}</span>
        </a>
      </div>
    </accordion-group>
  </accordion>

I need to remove the first <span class=badge> that displays {{sport.leagues.length}} and replace it with the sum of all {{league.offeringsAvailable}}. The number inside the gray badge represents the offeringsAvailable, which for MLB includes: 72,30,30,8,30

Therefore, instead of displaying sport.leagues.length in the yellow badge, I want to show the total sum of league.offeringsAvailable

This is the controller for sports

SportsFactory.getSportsWithLeagues().then(function(sports) {
  $scope.sports = sports;
  console.log(angular.toJson($scope.sports, 'pretty'));
});

The following

console.log(angular.toJson($scope.sports, 'pretty'));
provides this JSON data

Within the JSON structure, headers like LIVE BETTING contain an array of leagues with a property called offeringsAvailable. My goal is to extract each individual offeringsAvailable within a header like LIVE BETTING and calculate the total amount to be stored in a $scope variable in order to display it in the DOM.

[
  {
    "id": 26,
    "name": "LIVE BETTING",
    ... (additional data)
  },
  {
    "id": 6,
    "name": "MLB",
    ... (additional data)
  },
  {
    "id": 41,
    "name": "MLB  Props",
    ... (additional data)
  },
  ...

I am utilizing LODASH for iterating over arrays, but I'm unsure how to tackle this specific task

EDIT

Just to clarify, when I mentioned LIVE BETTING earlier, my intention is for the same process to occur for every sport within the array.

Answer №1

attempt:

// substitute in view
{{sport.leagues.length}}

// by
{{ total(sport) }}

//add scope method in controller
$scope.total = function(sport) {
    return _.sum(_.pluck(sport.leagues, 'offeringsAvailable'));
}

Answer №2

One efficient suggestion is to iterate through each sport data received and include an offerings attribute that consolidates the total number of offerings available.

sports.forEach(function(sport){ 
    sport.offerings=sport.leagues.reduce(function(prev,curr){     
        return prev + (curr.offeringsAvailable||0);
    },0);
});

Subsequently, in the header section, utilize {{sport.offerings}}

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

Tips for simulating JSON import using Jest in TypeScript

When it comes to unit testing in Typescript using Jest, I am looking to mock a .json file. Currently, I have a global mock set up inside my jest.config.js file which works perfectly: 'package.json': '<rootDir>/__tests__/tasks/__mocks ...

When attempting to compile at runtime without an instance, the act of creating a function constructor can lead to an

My website is designed to function as a simple quiz game. It retrieves an array of JSON questions using AJAX, and for each question in the array, it displays the question itself along with buttons containing various options that were stored in the question ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

Is there anyone who can assist me with the problem I'm facing where Javascript post call is sending a null value to my mongoDB

As a beginner in JS, NodeJS, and MongoDB, I decided to create a quiz website to sharpen my coding skills. However, I have encountered an issue while trying to send the username (string) and total marks (int) to MongoDB using the Post method. Surprisingly, ...

Locate records through an array of nested references using Moongoose (MongoDB)

Given the collection schema shown below: var terminalSchema = new mongoose.Schema({ name: 'String', ip: 'String' }); var wayPointSchema = new mongoose.Schema({ name: 'String', description: 'String' ...

PHP sending only a single space in an email

My HTML form works perfectly fine, except for one field! The issue arises with a particular text field that I fill out using a button and a short JavaScript function. Could this be causing a conflict with the PHP code? The problematic text field is: inpu ...

Sending a POST requestIs there an issue with performing

Below is my JavaScript code snippet: $('document').ready(function () { $('#filterSub').click(function (evt) { var data = $('form').serialize(); var gender = $('#gender').html(); $.post(& ...

Tips for using regular expressions with the find method in JavaScript?

Welcome to my Object: let data = [{ "title": "User info", "category": "personal", "userId": "abc12345" }, { "title": "Customer Info", "category": ...

What are some ways to handle JavaScript exceptions effectively?

Within my application, I am retrieving the content from a different domain's page. This content includes specific JavaScript that is executed alongside the page. However, there is an issue with the following line of code within the JavaScript: "docume ...

Is there a variation in IE6 versions depending on the operating system used?

It's puzzling to me that customers are reporting bugs on W2K machines in IE6, yet when I test locally on a WinXP System, everything appears normal. Could it be possible that there are differences in JavaScript Execution between the two systems? I do ...

Decreased storage space requirements following transfer to S3 bucket using nodejs

I am currently facing an issue with uploading files from a specific folder location to an S3 bucket using the nodejs aws-sdk. The files I am working with are deepzoom images (.dzi). While the files seem to be successfully uploaded to my S3 bucket, I have n ...

Combine the information from 3 separate subscriptions into a single object using RxJS in Angular 9

I am seeking assistance with merging data from 3 different sensors into one object. I am using Cordova plugins to retrieve accelerometer, gyroscope, and magnetometer data. However, I am facing an issue in subscribing to all three observables simultaneously ...

Tips for concealing a div when the mouse is moved off it?

My goal is to create a simple hover effect where hovering over an image within a view filled with images displays an additional div. This part works as expected. However, I'm facing issues when trying to hide the same div when the user moves out of t ...

Utilize the outcome of one variable to label another variable

I am attempting to generate a variable name by using the id value of another variable. Here is my approach: Upon clicking one of the 4 tables, I get the id of the table. For instance, let's say it's 676. Next, I want to create a variable using ...

creating a versatile axios function through object decomposition

Attempting to create a reusable axios function in my NodeJS project by parsing an object for multiple requests, and using the result of one request in subsequent ones. Previously hardcoded and chained axios requests, I need a more dynamic solution as the ...

Ways to incorporate validation into Material-UI form input fields

I have a react functional component that utilizes Material UI form, which includes TextField. The onChange event is managed in the "Container Component". I have added required for client-side form validation, but it doesn't seem to be working. Do I ne ...

Retrieve the values of each cell in a table row by utilizing jQuery

With the click of a button labeled "save", I aim to extract the data stored in each cell within a selected table row protected by a checkbox. Here's the scenario: When a user triggers the show table button, my page dynamically populates with informati ...

Exploring the FunctionDirective in Vue3

In Vue3 Type Declaration, there is a definition for the Directive, which looks like this: export declare type Directive<T = any, V = any> = ObjectDirective<T, V> | FunctionDirective<T, V>; Most people are familiar with the ObjectDirectiv ...

Encountering difficulties decoding URL-encoded data in Express

Here is a straightforward server I created: var app = require('express')(); var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.post('/update', (req, ...

Is there a way to nest arrays within arrays in JavaScript?

Array ( [0] => Array ( [contactId] => 5 [companyId] => 54 [personName] => Awais [contactNo] => 0321-1111111 [contactType] => Partner ) ) data[0].personName I ...