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

Anchoring HTTP headers in HTML tags

Currently, I am working on some code to enable dragging files from a web app to the desktop by utilizing Chrome's anchor element dragging support. The challenge I am facing is that certain file links require more than a simple GET request - they nece ...

Rendering issues arise in the app when utilizing browserHistory instead of hashHistory with React Router

I have integrated React Router into my current project in the following way: const store = Redux.createStore(bomlerApp); const App = React.createClass({ render() { return ( React.createElement('div', null, ...

React component fails to re-render after state change

For the past two days, I've been struggling with this error and can't seem to fix it! I'm currently working on creating a weather app in React which utilizes the API. The app features a Bootstrap Navbar with a search option that allows user ...

Saving Information from an HTML Form Input?

I am currently working on a form that collects information about employees including their name, age, position, and details. When the "Add Record" button is pressed, this information should be added to a designated div. Although I have set up the Object C ...

Perhaps dividing numbers with regular expressions

My HTML textarea allows users to input numeric serial numbers in various formats - either inline, separated by any character, or in columns from an Excel file. The serial codes are either 14 characters long if the first character is "1," or always 15 char ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Utilizing jQuery for AJAX-Based Deletion of Records

Hey, I stumbled upon a code snippet that allows me to delete a row from my database using Ajax. However, there seems to be an issue where the table that should disappear when deleted is not working properly. Here is the JavaScript code: <script type=" ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

The Vue component should trigger the display of data in a Bootstrap modal based on the row of the button that was

Here is a sample code snippet demonstrating how data is fetched from the database: <table class="table table-bordered"> <thead> <tr><th>User ID</th><th>Account Number</th><th>Accou ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date. getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) { var date = new Date(millisSinceEpoch); if (d ...

Error: Unable to locate corresponding closing tag for "<%"

I'm struggling to figure out what I might have missed. Everything appears correct, but the nested and somewhat complex code that I am writing seems to be causing an issue with EJS. The variable posts has been passed from node.js to the EJS file. How c ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

The AngularJS filter with momentjs for dates is producing excessive output

Currently, I am fetching data from Laravel using a GET request with angularJS. The output looks like this: "vacations":[ { "id":1, "timeschedule_id":1, "begindate":"2017-04-28 00:00:00", "enddate":"2017-04-30 00:00:00", ...

Improving Angular factory's counter with socket.io integration

I am currently working on a solution to automatically update the number of incoming data. I have set up a system to listen for incoming messages and count them in a factory: angular.module('app') .factory('UpdateCounter', ['s ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...