A guide on organizing and categorizing data by name with angularjs

Presented here is a list of descriptions associated with specific names. I am seeking guidance on how to group or list the descriptions by name.

html:

<body ng-app="app" ng-controller="MainCtrl">

    <div ng-repeat="nameGroup in loopData"> <!-- Scope for this ng-repeat should be customizable -->
        <div ng-repeat="loopData in nameGroup.values track by $index" ><!-- Scope for this ng-repeat should be customizable -->

        <div class="text-center merged">{{loopData.name}}</div><!-- ng-if="$index === 0" -->
        <div class="text-center">{{loopData.description}}</div> 

     </div>
     </div>
</body>

controller:

var app = angular.module('app', ['angular.filter']);

app.controller('MainCtrl', function($scope) {
  $scope.finalLoopData = {};

  $scope.loopData = [{ "country":"Abc", "id":"001", "mynumbers":[], 
    "values": [
      {"description": "first desc", "name": "First Test Name"},
      {"description": "second desc", "name": "First Test Name"},
      {"description": "third desc", "name": "First Test Name"},
      {"description": "fourth desc", "name": "Second Test Name"},
      {"description": "fifth desc", "name": "Second Test Name"},
      {"description": "sixth desc", "name": "Third Test Name"},
      {"description": "seventh desc", "name": "Third Test Name"},
      {"description": "eighth desc", "name": "Third Test Name"},
      {"description": "ninth desc", "name": "Third Test Name"},
      {"description": "tenth desc", "name": "Third Test Name"},
      {"description": "eleventh desc", "name": "Fourth Test Name"},
      {"description": "twelfth desc", "name": "Fourth Test Name"}
    ]
  }];

  $scope.arrayToObject = function () {
    var finalLoopData = {};
    angular.forEach($scope.loopData[0].values, function (value, key) {
        if (!finalLoopData[value.name]) { 
             finalLoopData[value.name] = new Array();
        }
        finalLoopData[value.name].push(value);
    });
    $scope.finalLoopData = finalLoopData;
  }
  $scope.arrayToObject();
});

Upon executing the code, individual descriptions with names are generated. However, my desired output should resemble the following:

First Test Name

  • first desc

  • second desc

  • third desc

Second Test Name

  • fourth desc

  • fifth desc

Third Test Name

  • sixth desc

  • seventh desc

  • eighth desc

  • ninth desc

  • tenth desc

Fourth Test Name

  • eleventh desc

  • twelfth desc

Developed Filter:

Answer №1

Refreshed Version

If modifying the loops in the template is not feasible, you can try the following alternative approach:

Template Adjustment

<body ng-app="app" ng-controller="MainCtrl">
  <!-- Existing loops -->
  <div ng-repeat="nameGroup in loopData">
    <div ng-repeat="loopData in nameGroup.values track by $index">

      <!-- Data label -->
      <strong>{{loopData.name}}</strong>

      <!-- Loop data categorizations -->
      <ul ng-repeat="description in loopData.descriptions">
        <li>{{description}}</li>
      </ul>

    </div>
  </div>
</body>

Controller Update

var app = angular.module('app', ['angular.filter']);

app.controller('MainCtrl', function($scope) {

  $scope.loopData = [
    {
      country: "Abc",
      id: "001",
      mynumbers: [],
      values: [
        { description: "first desc", name: "First Test Name" },
        { description: "second desc", name: "First Test Name" },
        { description: "third desc", name: "First Test Name" },
        { description: "fourth desc", name: "Second Test Name" },
        { description: "fifth desc", name: "Second Test Name" },
        { description: "sixth desc", name: "Third Test Name" },
        { description: "seventh desc", name: "Third Test Name" },
        { description: "eighth desc", name: "Third Test Name" },
        { description: "ninth desc", name: "Third Test Name" },
        { description: "tenth desc", name: "Third Test Name" },
        { description: "eleventh desc", name: "Fourth Test Name" },
        { description: "twelfth desc", name: "Fourth Test Name" }
      ]
    }
  ];

  this.$onInit = function() {
    $scope.loopData.forEach(function(data) {
      const groupedValues = {};

      // group values based on name
      data.values.forEach(function(value) {
        // initialize name group
        if (!groupedValues[value.name]) {
          groupedValues[value.name] = {
            name: value.name,
            descriptions: []
          };
        }

        // add description to name group
        groupedValues[value.name].descriptions.push(value.description);
      });

      // update values
      data.values = Object.values(groupedValues);
    });
  };

});

Note that the $onInit method will transform $scope.loopData into the new structure as shown below:

[
  {
    "country": "Abc",
    "id": "001",
    "mynumbers": [],
    "values": [
      {
        "name": "First Test Name",
        "descriptions": [
          "first desc",
          "second desc",
          "third desc"
        ]
      },
      {
        "name": "Second Test Name",
        "descriptions": [
          "fourth desc",
          "fifth desc"
        ]
      },
      {
        "name": "Third Test Name",
        "descriptions": [
          "sixth desc",
          "seventh desc",
          "eighth desc",
          "ninth desc",
          "tenth desc"
        ]
      },
      {
        "name": "Fourth Test Name",
        "descriptions": [
          "eleventh desc",
          "twelfth desc"
        ]
      }
    ]
  }
]

Initial Response

In your HTML code, you need to iterate over the processed variable finalLoopData. Additionally, to display the group name once, it should be included in the primary loop rather than the secondary loop.

You may consider utilizing the following snippets:

Adjusted Template

<body ng-app="app" ng-controller="MainCtrl">
  <!-- Iterating through final data -->
  <div ng-repeat="nameGroup in finalLoopData">

    <!-- Displaying Group name -->
    <strong>{{nameGroup.name}}</strong>

    <!-- Listing group descriptions -->
    <ul ng-repeat="description in nameGroup.descriptions track by $index">
      <li>{{description}}</li>
    </ul>

  </div>
</body>

Update in Controller

var app = angular.module('app', ['angular.filter']);

app.controller('MainCtrl', function($scope) {

  $scope.finalLoopData = {};

  $scope.loopData = [
    {
      country: "Abc",
      id: "001",
      mynumbers: [],
      values: [
        { description: "first desc", name: "First Test Name" },
        { description: "second desc", name: "First Test Name" },
        { description: "third desc", name: "First Test Name" },
        { description: "fourth desc", name: "Second Test Name" },
        { description: "fifth desc", name: "Second Test Name" },
        { description: "sixth desc", name: "Third Test Name" },
        { description: "seventh desc", name: "Third Test Name" },
        { description: "eighth desc", name: "Third Test Name" },
        { description: "ninth desc", name: "Third Test Name" },
        { description: "tenth desc", name: "Third Test Name" },
        { description: "eleventh desc", name: "Fourth Test Name" },
        { description: "twelfth desc", name: "Fourth Test Name" }
      ]
    }
  ];

  this.$onInit = function() {
    const finalLoopData = {};
    $scope.loopData[0].values.forEach(function(item) {
      // Initializing name group
      if (!finalLoopData[item.name]) {
        finalLoopData[item.name] = {
          name: item.name,
          descriptions: []
        };
      }

      // Adding description to name group
      finalLoopData[item.name].descriptions.push(item.description);
    });

    // Applying the changes
    $scope.finalLoopData = finalLoopData;
  };

});

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

"I'm encountering an issue with the discord.js module when I try to launch my bot using node. Any ideas on how

I encountered an unusual error with my Discord bot recently. It seems that discord.js crashes every time I try to run my bot: [nodemon] 2.0.12 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mj ...

The issue with Three.Js Raycasting arises when attempting to change camera transformations within an Object3D parent element

In my latest project, I decided to create a "camera controller" that handles the movement and rotation of the camera by utilizing an Object3D as its parent. The Y-axis rotations are applied to the Object3D, while the X-axis rotation is directly applied to ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...

What is the process for selecting the default option in a drop-down menu?

Is there a way to set the default value in a drop-down list using material-ui? I attempted to use displayEmpty="true", but it did not work. I want the first option, A, to be pre-selected so that it is visible to the user in the UI without them having to m ...

UI is experiencing lag issues post Alert invocation in React Native

// When a text field is pressed, an alert function is called. This function opens an alert and then calls another function on confirmation. However, the application gets stuck when "showAlert1()" is called, and this function is being invoked multiple times ...

Event handler assigned to a group of constantly changing elements

Here is my JavaScript code: $(document).ready(function(){ $('#data1').change(function(){ title = $('#title1').val(); url = $('#url1').val(); $.post('library/edit.php',{title:title, url:ur ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

What is the most effective method for displaying two external web pages next to each other?

Looking for a solution to display an English Wikipedia article on the left side of the page alongside its Spanish version on the right side. Wondering if it's possible using HTML, JavaScript, AJAX, etc. I am aware that I could use iframes, but I woul ...

Can LocalStorage be deleted when the application is not running?

Can a specific key in an application's LocalStorage be deleted without having to open the app? I'm considering creating a batch file script for removing a particular key from the app's LocalStorage while the app is not running. The challeng ...

Leverage JSON data from an API within JavaScript, sourced and accessed through PHP

I'm seeking advice on using JSON data (loaded in PHP) with JavaScript. I am currently retrieving the JSON from an API, but someone suggested that using curl would be more efficient? I've attempted to research curl, but haven't found exactly ...

Transforming JSON data into a visual flowchart using VUE.js

In the project I am currently working on, I am faced with the challenge of importing a JSON file (exported from a flowchart drawing project) and converting its data into an actual flowchart. Unfortunately, I have not been able to find any leads on how to c ...

Graph is not showing up when navigating through page

On my List page (List.Html), users can select multiple rows to display the data in a chart using C3. However, when clicking on the compareList() button to navigate to the Chart page (Chart.Html), the chart does not display properly. It seems that the chart ...

Issue: The DLL initialization routine failed for electron, but it works perfectly fine on node.js

Currently, I am facing an issue while attempting to load a custom module in electron that is written in D using the node_dlang package. The module loads successfully with node, but encounters failures within electron. The test run with node, which works w ...

What is the process of sending a modified array as text to TextEdit?

As a beginner in JXA, I am currently learning how to perform simple tasks in TextEdit. I have managed to extract the paragraphs of a document and store them as an array using the following code: app = Application('TextEdit') docPars = app.docu ...

Drawbacks of adjusting design according to screen width via javascript detection

When creating a website, I want it to be compatible with the most common screen resolutions. Here is my proposed method for achieving this: -Develop CSS classes tailored to each screen resolution, specifying properties such as width and position. -Write ...

Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work. Here is my first controller: app.controller('mycont1', [' ...

Steps to turn off sourcemaps in the @sentry/nextjs package

Currently, I am working on a Next.js project and have incorporated the @sentry/nextjs package for error logging purposes. My goal is to turn off sourcemaps in the client side of my deployed application. Despite going through this informative blog post fro ...

Why bother re-rendering components in React that haven't had any changes in their state?

Within my main component, I have both a state and a static component nested inside. An issue arises when the state changes and triggers a re-render of the main component, causing the static component to also re-render unnecessarily. import { useState } fro ...

What is the best way to access a custom object in JavaScript that was created in a different function?

Currently working with JavaScript and jQuery technology. In one of my functions that runs on document ready, I am creating objects with different attributes. While I can easily access these object attributes within the same function, I'm facing diff ...

Docz: Utilizing Typescript definitions for props rendering beyond just interfaces

We are currently using Docz to document our type definitions. While it works well for interfaces, we've run into an issue where rendering anything other than interfaces as props in Docz components doesn't seem to display properly. I'm seeki ...