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

Is there a way to store a SAFEARRAY (an array of bytes) into an HTML hidden field?

Is there a way to extract an array of bytes from an active-x component, save it in an html-form input hidden field, and then send it to the server using form-submit? I'm not sure how to accomplish this. MIDL: HRESULT Data([out, retval] SAFEARRAY(VAR ...

Modify the colors of Highcharts columns based on the individual political parties

I have successfully implemented a column chart here. My goal now is to modify the color of the columns based on the political party: red for Republican, blue for Democratic, and default colors for Third-Party and Unknown/Not Designated. I'm unsure abo ...

The index.html file is failing to load/render when using app.js

I am currently in the process of creating a to-do list using an older tutorial. The app.js file seems to be functioning properly, however, when I try to run it locally, all I see is a blank page instead of my HTML content. Here is the code found in the ap ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Tips for saving the file path locally using local storage in AngularJS

My attempt at using $localstorage to store the file path locally and preview it using an iframe is resulting in an error. $scope.getResume = function() { var resumeJson = { "json":{ "request":{ ...

What could be causing the issue with the exports field in package.json not functioning properly within

Recently, I created an npm package that includes three js files. Now, in my current project, I am aiming to import these js files using the following syntax: import MyButton from '@bslm/ui/MyButton' To achieve this, I made sure to specify the ex ...

Tips for correctly loading API data into dependent tableViewCells

Working on a UITableView that makes 2 API calls for every cell has been successful until today. Recently, I encountered a major issue where there were more cells on the screen than actually loaded. While scrolling down the tableView, the screen froze for ...

Is there a way to update an angular.js service object without using extend or copy?

I am working with 2 services and need to update a variable in the first service from the second service. Within a controller, I am assigning a scope variable to the getter of the first service. The issue I am facing is that the view connected to the cont ...

The significance of using the Spread operator in React-Redux Reducers

Exploring the essence of the spread operator has been quite intriguing. Based on my interpretation of the documentation, it seems that the spread syntax essentially duplicates the existing object and then gets replaced by a new object when one is introduce ...

Difficulty encountered while executing JavaScript in Chrome 78 with Python and Selenium, as pages are not switching

I have encountered an issue with my script that switches between site pages containing tables. Everything was working smoothly for months with Chrome version 76, but after updating to the new Chrome version 78.0.3904.70, an error has arisen: driver.execu ...

Need assistance as require function is not functioning as anticipated

const THREE = require('three'); require('three/examples/js/loaders/OBJLoader.js'); Once I imported threejs from node_modules, I decided to utilize the provided OBJLoader, but encountered an unexpected error. THREE is not defined a ...

I'm looking for a creative JavaScript prototype example that can help illustrate the concept of prototypes. Can someone share an interesting sample with me

I've been trying to wrap my head around prototypes, but I just can't seem to grasp their purpose and function. Is there anyone who can provide a straightforward example (such as a collegeStudent object) that will clarify the fundamentals of proto ...

Struggling to grasp the concept of DOM Event Listeners

Hello, I have a question regarding some JavaScript code that I am struggling with. function login() { var lgin = document.getElementById("logIn"); lgin.style.display = "block"; lgin.style.position = "fixed"; lgin.style.width = "100%"; ...

I am struggling with clicking on Bootstrap's pagination using AngularJS

I'm still getting the hang of Angularjs. I managed to set up a pagination system, but for some reason, I can't seem to interact with it when I run my project. Take a look at this screenshot that illustrates my issue: https://drive.google.com/fil ...

Retrieving Data from ArrayLists in Java

Is there a way to extract the data in the following format? I am looking to retrieve from this arraylist: [{itemname=Original, number=12}, {itemname=BBQ, number=23}, {itemname=CatchUp, number=23}] The desired array should look like this: {"Original":12 ...

Navigating through concatenated JSON strings in a web browser: A step-by-step guide

I am currently using Socket.IO to transmit data to the browser. The information being sent is a continuous stream of JSON objects, which upon arrival at the browser, transforms into a single large JSON string. However, the issue I am encountering is that t ...

iOS Ionic Camera Plugin

I've encountered a common issue that I haven't been able to solve despite trying many solutions. While running my Ionic app on my IOS device, the camera plugin coding is returning undefined values and getting stuck before reaching the options va ...

Is there a way for me to write on a website and have my content instantly show up on a different hosting

Similar Question: Web based text chat? I am looking to develop a website that enables me to type in a textbox and have the content displayed on another user's screen. Can anyone assist me with this task? Thank you! Amen ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

Guide on using Encodable or Decodable as a parameter in Swift 4

Currently, I am in the process of learning JSONParsing. After going through various tutorials, I have implemented the following code: guard let url = URL(string: "http://localhost/test-api/public/api/register") else { return } var request = URLR ...