Enhancing AngularJS: Tailored iterations and data manipulations for more advanced grouping beyond basic ng-repeat limitations

Although I found the answer to this issue on Angular.js more complex conditional loops satisfactory and accepted it, I feel there is more to discuss.

Let me provide further details that were not included in my initial inquiry.

My goal is to transform the following:

<h3>11.4.2013</h3>
<ul>
 <li>oofrab | 4 | 11.4.2013 14:55 <button>remove</button></li>
 <li>raboof | 3 | 11.4.2013 13:35 <button>remove</button></li> 
</ul>

<h3>10.4.2013</h3>
<ul>
 <li>barfoo | 2 | 10.4.2013 18:10 <button>remove</button></li>
 <li>foobar | 1 | 10.4.2013 12:55 <button>remove</button></li>
</ul>

into this data structure:

[
    {
        "id": 4,
        "name": "oofrab",
        "date": "2013-11-04 14:55:00"
    },
    {
        "id": 3,
        "name": "raboof",
        "date": "2013-11-04 13:55:00"
    },
    {
        "id": 2,
        "name": "barfoo",
        "date": "2013-10-04 18:10:00"
    },
    {
        "id": 1,
        "name": "foobar",
        "date": "2013-10-04 12:55:00"
    }
]

In addition to standard ng-repeat, I specifically want to include those headings. However, the process seems unnecessarily complicated despite the provided solution.

The implementation derived from the first question can be viewed here: http://plnkr.co/edit/Zl5EcsiXXV92d3VH9Hqk?p=preview

It's important to note that the system could potentially handle up to 400 entries while allowing for dynamic entry manipulation.

The plunker example achieves the desired outcome by:

Iterating through the original data to create a new structured object as shown below:

{
  "2013-10-05": [
    {
      "id": 4,
      "name": "oofrab",
      "date": "2013-10-05 14:55:00",
      "_orig_index": 0
    },
    {
      "id": 3,
      "name": "raboof",
      "date": "2013-10-05 13:55:00",
      "_orig_index": 1
    }
  ],
  "2013-10-04": [
    {
      "id": 2,
      "name": "barfoo",
      "date": "2013-10-04 18:10:00",
      "_orig_index": 2
    },
    {
      "id": 1,
      "name": "foobar",
      "date": "2013-10-04 12:55:00",
      "_orig_index": 3
    }
  ]
}

This allows for the desired result to be attained through the following approach:

<div ng-repeat="(date,subItems) in itemDateMap">
<h3>{{date}}</h3>
<ul>
  <li ng-repeat="item in subItems">
    {{item.name}} | {{item.id}} | {{item.date}}
    <button type="button" ng-click="removeItem(item._orig_index)">x</button>
  </li>
</ul>  
</div>

Despite achieving the intended outcome, significant drawbacks persist. The need to rebuild the itemDateMap each time a new entry is added or removed, date alterations are made, or an item needs to be deleted proves cumbersome. Additionally, performance issues arise when handling a large number of entries.

This convoluted process goes against the simplicity of the task at hand.

How should I proceed?

Answer №1

I propose streamlining your code by utilizing one structure and exposing only the map to the scope. Create a function to add an array of items to the map and another function to transform the map into an array, which may be necessary for server communication.

  var toKey=function(item){
    return moment(item.date).format("YYYY-MM-DD");
  }

  $scope.itemDateMap = {};
  $scope.addItemToDateMap=function(item){
    var key = toKey(item);
    if(!$scope.itemDateMap[key]){
      $scope.itemDateMap[key] = [];
    }
    $scope.itemDateMap[key].push(item);    
  }

  $scope.removeItemFromDateMap=function(item){
    var key = toKey(item), subitems = $scope.itemDateMap[key];
    var index = subitems.indexOf(item);
    subitems.splice(index,1);
    if(subitems.length === 0){
      delete $scope.itemDateMap[key];
    }
  }

  var addArrayToMap = function(items){
    for(var i=0; i<items.length; i++){
      var item = items[i]; 
      $scope.addItemToDateMap(item);
    }
  };

  $scope.mapToArray = function(){
    var items = [];
    for(var key in $scope.itemDateMap){
      var subitems = $scope.itemDateMap[key];
      for(var j=0;j<subitems.length;j++){
        var item = subitems[j];
        items.push(item);
      }
    }
    return items;
  }

You can view my updated suggestion on Plunker. I believe this solution is efficient.

If you require sorting, consider using the following structure (array with objects containing arrays) so that you can utilize orderBy:'date' on the root array:

[
{
  date:"2013-10-05",
  items: [
    {
      "id": 4,
      "name": "oofrab",
      "date": "2013-10-05 14:55:00"
    },
    {
      "id": 3,
      "name": "raboof",
      "date": "2013-10-05 13:55:00"
    }
  ]
},
{
  date:"2013-10-04",
  items: [
    {
      "id": 2,
      "name": "barfoo",
      "date": "2013-10-04 18:10:00"
    },
    {
      "id": 1,
      "name": "foobar",
      "date": "2013-10-04 12:55:00"
    }
  ]
}
]

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 preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Export data from a JSON object to a CSV file within the Osmosis function

I am currently utilizing Osmosis, a node.js tool, to extract data in the form of an array of JSON objects. The behavior of Osmosis functions indicates that the array is confined within the function's scope. Consequently, I must also write the file in ...

Exploring JSON and jQuery to Address Filtering Challenges

Excuse the interruption, but I need some assistance with my filters. Below is the code I'm currently working on; however, none of my attempts have been implemented yet (the dropdown menu and checkboxes remain non-functional) to make it easier for you ...

Identical Identifiers in jQuery Tab Elements

Currently, I am utilizing the jQuery Tabs library within a small application. Within this page, there are 5 tabs that load content using Ajax. However, an issue arises when a tab is loaded and remains in the browser's memory along with its HTML elemen ...

The Material UI Menu does not close completely when subitems are selected

I am working on implementing a Material UI menu component with custom MenuItems. My goal is to enable the closure of the entire menu when clicking outside of it, even if a submenu is open. Currently, I find that I need to click twice – once to close the ...

Preventing links from functioning on dynamically generated web pages

I have implemented the following code to deactivate all links on a preview page: var disableLink = function(){ return false;}; $('a').bind('click', disableLink); While this successfully disables all static links, any anchor tags loade ...

JavaScript - filter out values not included in specified list of attributes

I am seeking a technique that, when provided with a list of attributes, retains only the values associated with keys present in the list. For instance: attrs = ['a', 'b', 'c'] obj = {'a': 1, 'b': 2, &apos ...

Change the size of a particular div upon hovering over another element

I'm trying to figure out how to scale my div with text when a user hovers over a button, but I've tried various operators like >, ~, +, - with no success. section { background: #000; color:#fff; height: 1000px; padding: 150px 0; font-family ...

Retrieving an HTML element that has been added through DOM manipulation

After successfully creating a Jquery function that inserts a 'save button' into the page when a specific button is clicked, I encountered an issue with another function meant to be activated when the save button is clicked. The first function see ...

There seems to be an issue with Vue JS slots[name$1].every function as it is

I attempted to implement a custom isEmpty function for the Object prototype as follows: Object.prototype.isEmpty = function() { for (var key in this) { if (this.hasOwnProperty(key)) { return false } } return true } However, when tryin ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

A comprehensive guide on implementing filtering in AngularJS arrays

I am working with the array provided below: [ { Id: 1, Name: "AI", Capacity: 2, From: "2021-10-27T08:00:00", To: "2021-10-27T08:50:00", }, { Id: 2, Name: "TEST", Capacity: 2, ...

Update the text for the filter search placeholder in the Ant Table component

Is there a way to alter the default placeholder text in the Ant Table? I've set up a functioning example in documentation but couldn't find any prop for customization besides the customized filter dropdown, which I didn't want to implement. ...

Is it Feasible to Have Angular 1.4 View Encapsulation and Shadow DOM Integration?

Currently, I am in the process of transitioning my app from Polymer to Angular 1.4 due to stability concerns. Given my experience with Polymer and web components, as well as the future integration of Angular 2, I have decided to structure my app using the ...

The D3 data format allows for creating interactive sunburst charts that can be easily zoom

My data is structured similarly to flare.json as shown in this example: I'm curious about the function used by the d3 zoomable chart to format the data in this way. The original structure in flare.json looks like this: { name: "stuff", childr ...

Retrieve data from MongoDB using the find() method results in an empty response, however,

While working on a project to practice my MongoDB skills, I encountered an issue with retrieving all the data from MongoDB. Despite receiving a successful 200 response, I was unable to properly extract all the data. Using Express framework for this task, ...

How to Identify and Print a Specific Property in a JSON Object using Node.js?

Hey there, I'm having trouble extracting the trackName from the JSON object provided here. I've tried accessing it using this code: console.log(res.text.results[0].trackName); but unfortunately, I keep getting this error message: TypeError: Cann ...

Guide to changing the color of SVG images on a live webpage

I'm having trouble changing the color of a specific part within an svg image (created in Inkscape). I believe CSS is the solution, but I can't seem to select the id from the particular SVG file. The object in the SVG has the id='ToChange&apo ...

Issues with Angular Material Pagination functionality may be causing unexpected behavior

I'm facing an issue with displaying data in an HTML table using an API. I've tried to implement pagination to show 3 or 6 rows per page, but it's not working as expected. Currently, all the data is being displayed without any pagination, whe ...