Utilize underscore's groupBy function to categorize and organize server data

I am currently utilizing Angular.js in conjunction with Underscore.js

This is how my controller is structured:

var facultyControllers = angular.module('facultyControllers', []);
facultyControllers.controller('FacultyListCtrl', ['$scope','FacultyListFactory', function($scope, FacultyListFactory) {
  //Retrieve JSON data from the server via factory
  $scope.speakers = FacultyListFactory.query();

  //Group speakers by last name letter for indexing
  $scope.groups = _.groupBy($scope.speakers['faculty'], "lastNameStartsWith");
}]);

Here is a glimpse of my view design:

<section id="faculty-list">
    <div ng-repeat="(lastNameStartsWith, speakers) in groups">
       <h3 id="{{lastNameStartsWith}}" class="faculty-list-header">{{lastNameStartsWith}}</h3>
       <article class="faculty-list-repeater" ng-repeat="speaker in speakers | filter: facultyFilter | orderBy:'last'">
           <div class="row">
           ...
           <div class="col-xs-10">
               <ul class="faculty-short-detail list-unstyled">
                  <li class="name">{{speaker.displayAs}}</li>
                  ...
               </ul>
           </div>
           </div>
        </article>
    </div>
</section>

The format of the JSON received from the server is as follows:

{
    "faculty":[
    {displayAs: 'John', lastNameStartsWith: 'A', firstName:'John', age:25, gender:'boy'},
    {displayAs:'Jessie', lastNameStartsWith: 'E', age:30, gender:'girl'},
    {displayAs:'Johanna', lastNameStartsWith: 'F', age:28, gender:'girl'},
    {displayAs:'Joy', lastNameStartsWith: 'F', age:15, gender:'girl'},
    {displayAs:'Mary', lastNameStartsWith: 'G', age:28, gender:'girl'},
    {displayAs:'Peter', lastNameStartsWith: 'L', age:95, gender:'boy'},
    {displayAs:'Sebastian', lastNameStartsWith: 'O', age:50, gender:'boy'},
    {displayAs:'Erika', lastNameStartsWith: 'T', age:27, gender:'girl'},
    {displayAs:'Patrick', lastNameStartsWith: 'V', age:40, gender:'boy'},
    {displayAs:'Samantha', lastNameStartsWith: 'Z', age:60, gender:'girl'}
    ]
};

The issue I am encountering arises when attempting to log $scope.speakers; it shows a resource and nesting arrays under faculty. If I substitute the JSON directly into my controller instead of using FacultyListFactory.query(); I can successfully execute $scope.groups = _.groupBy($scope.speakers['faculty'], "lastNameStartsWith");. However, it's not feasible to insert all the JSON directly due to numerous entries fetched from the server. When I try accessing the server through $scope.groups = .groupBy($scope.speakers['faculty'], "lastNameStartsWith"); an empty object is displayed in the console log, denoted by console.log(.groupBy($scope.speakers['faculty'], "lastNameStartsWith"));.

When I replace $scope.groups = _.groupBy($scope.speakers, "lastNameStartsWith"); I receive undefined because data resides within {"faculty":[...]}

I'm baffled on how to access the nested array beneath a key value from data extracted from a GET call. It's imperative to group by last name letter for this list, and despite spending hours trying to resolve the issue, I'm uncertain why 'faculty' isn't functioning as expected. Any assistance would be greatly appreciated! Thank you.

Answer №1

Organize the data using lodash's <code>_.groupBy
, like this: $scope.groups = _.groupBy(...);. Make sure to place it inside the success callback of the query() function to ensure it executes only after the data has been fetched...

To implement this, update your code as follows:
$scope.speakers = FacultyListFactory.query(function (data) { 
    $scope.groups = _.groupBy($scope.speakers['faculty'], "lastNameStartsWith"); 
}, function(error) { // error handler });

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

Need help speeding up website load times?

My website is loading incredibly slow, even though it has minimal content. I suspect that the high number of images and JavaScript elements on the page are contributing to this issue. Is there a method available to diagnose what exactly is causing the ext ...

Module Express - Transferring Object to Main Application

Having issues with passing an object in Express from a module to my application. The process is straightforward - gathering input from a form, validating the string, and returning either null or an object. Despite trying various methods, I'm still fac ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...

Having trouble with closing modal pop-up window after submitting the form

angular.module("simpleModalPop").controller("applicationListCtrl", [ "$scope", "masterService", "$rootScope", "Notification", "applicationService", "Constant", "$filter", "$state","$uibModal", function($scope, masterService, $rootScope, Notification, a ...

Discover distinct and recurring elements

Having two sets of JSON data: vm.userListData = [{ "listId": 1, "permission": "READ" }, { "listId": 2, "permission": "WRITE" }, { "listId": 2, "permission": "READ" }, { "listId": 3, ...

Encountering an Issue while Deploying a create-react-app to Heroku

Despite trying various online remedies, I am still encountering an error while attempting to deploy a simple React.js app on Heroku. The app successfully builds when I execute git push heroku master, but upon opening it, I consistently receive an applicati ...

Unraveling Complex JSON Structures in Swift 4 with Optional Keys

Deciphering the JSON data obtained from is my current challenge. At times, certain values in the data can be nil, and I prefer not to make all properties optional. To tackle this, I am exploring custom decoding methods. [ { "ID": "e83bf033-db ...

Every time I use Axios with NextJS, I keep getting a frustrating 405 method not allowed

I am facing a challenging issue with this... Currently, I am using NextJS for the frontend and making a request to <frontend-domain>/api/auth/register from here. const changePassword = async (currentPassword, password) => { await axios.post(& ...

Angular JS: Extracting the header from a CSV file

Just getting started with angular JS and I have a question. I need to take a CSV file from the user as input and then send it to the controller when they click submit. <button class="btn btn-primary" type="submit" ng-click="Input(File)">Submit</ ...

Struggling to iterate through JSON data in Office Scripts?

My task involves parsing JSON data in Office Scripts to extract the headings and row details on a spreadsheet. While I have successfully fetched the data, I am encountering an error message stating that my information is not iterable at the "for" loop. ...

What are the performance differences between using Redis strings and Redis hashes for storing JSON data?

When it comes to storing a JSON payload in Redis, there are two main methods to consider: The first method involves using simple string keys and values. key:user, value:payload (the entire JSON blob which can be 100-200 KB) SET user:1 payload The seco ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

If viewed on a mobile device, separate the array (indexed list) into two rows

Currently, I am working on my Ionic project where I am trying to implement an indexed list horizontally instead of vertically. While the list looks good as it is now, I want to make sure it supports smaller screen devices too by splitting the list into two ...

Concealed from view, the act of sending HTTP requests takes

Currently utilizing the ionic framework and in need of fetching all details pertaining to the current user. With a vast amount of data, I am looking to display a progress bar on the header along with a counter indicating the remaining data being downloaded ...

Transform JSON structure (Group data)

Here is the JSON object I am working with: [{ "name" : "cat", "value" : 17, "group" : "animal", }, { "name" : "dog", "value" : 6, "group" : "animal", }, { "name" : "snak", "value" : 2, "group" : "animal", }, { "na ...

Changing nested JSON into a flat dataframe in R

Here is the structure of my JSON: I am looking to convert it into a flat dataframe. res <- jsonlite::fromJSON(data, simplifyDataFrame=TRUE) or res <- jsonlite::fromJSON(data, flatten=TRUE) However, these methods give strange results. I have t ...

Can you please provide instructions on how to implement an ng-repeat loop within an HTML table?

<thead> <tr> <th ng-click="sortData('firstname')"> Firstname <div ng-class="getSortClass('firstname')"></div> ...