Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from 'Chandigarh', and so on. How can I achieve this?

Below is a snippet of my code:

                    <a href="#" ng-repeat="r in resturant" id="rest-list-f" class="offVal">
                        <div class="col-md-6 col-centered form-planner-inner">
                            <span class="form-text">{{ r.Name }}</span><br>
                            <address><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span> &nbsp;{{ r.Address }}</address>
                            <img class="img-responsive" src="{{ r.Image }}" alt="{{ r.Name }} Image"><br>
                            <hr/>
                            <table class="eventActive">
                                <caption><strong><center><a href="#">Click To Read Reviews</a></center></strong></caption>
                                <tr>
                                    <td><span class="glyphicon glyphicon-cutlery" aria-hidden="true"></span> &nbsp;{{ r.Type }}</td>
                                    <td><span class="glyphicon glyphicon-time" aria-hidden="true"></span> &nbsp;{{ r.Hours }}</td>
                                </tr>
                            </table>
                        </div>
                    </a>

This is a snippet of my JSON Code:

   {
  "records": [
    {
      "Name": "Sagar Ratna",
      "Image": "./images/sr.jpg",
      "Address": "Mohali",
      "Type": "South Indian",
      "Hours" : "10:00-23:30"
    },
    {
      "Name": "The Night Factory",
      "Image": "./images/nf.jpg",
      "Address": "Chandigarh",
      "Type": "Chinese",
      "Hours" : "24/7"
    },
    {
      "Name": "Whistling Duck",
      "Image": "./images/ed.jpg",
      "Address": "Rajpura",
      "Type": "Chinese",
      "Hours" : "11:30-23:30"
    },
    {
      "Name": "Uncle Jack's",
      "Image": "./images/uj.jpg",
      "Address": "Mohali",
      "Type": "Pizza",
      "Hours" : "10:00-22:30"
    },
    {
      "Name": "Corner Griller",
      "Image": "./images/cg.jpg",
      "Address": "Rajpura",
      "Type": "North Indian",
      "Hours" : "11:00-23:30"
    },    {
      "Name": "Starbucks",
      "Image": ./images/st.jpg",
      "Address": "Delhi",
      "Type": "Coffee",
      "Hours" : "24/7"
    }
  ]
}

This is how I want the output to look like :

<div> Restaurant Name, Address: Delhi </div>
<div> Restaurant Name, Address: Mohali </div>
<div> Restaurant Name, Address: Mohali </div>
<div> Restaurant Name, Address: Rajpura </div>  
<div> Restaurant Name, Address: Rajpura </div>
<div> Restaurant Name, Address: Rajpura </div>
<div> Restaurant Name, Address: Chandigarh </div>

Answer №1

Your code has been modified slightly. Give this a try.

JSON

  $scope.Restaurents =  {
  "records": [
    {
      "Name": "Sagar Ratna",
      "Image": "./images/sr.jpg",
      "Address": "Mohali",
      "Type": "South Indian",
      "Hours" : "10:00-23:30"
    },
    {
      "Name": "The Night Factory",
      "Image": "./images/nf.jpg",
      "Address": "Chandigarh",
      "Type": "Chinese",
      "Hours" : "24/7"
    },
    {
      "Name": "Whistling Duck",
      "Image": "./images/ed.jpg",
      "Address": "Rajpura",
      "Type": "Chinese",
      "Hours" : "11:30-23:30"
    },
    {
      "Name": "Uncle Jack's",
      "Image": "./images/uj.jpg",
      "Address": "Mohali",
      "Type": "Pizza",
      "Hours" : "10:00-22:30"
    },
    {
      "Name": "Corner Griller",
      "Image": "./images/cg.jpg",
      "Address": "Rajpura",
      "Type": "North Indian",
      "Hours" : "11:00-23:30"
    },    
    {
      "Name": "Starbucks",
      "Image": "./images/st.jpg",
      "Address": "Delhi",
      "Type": "Coffee",
      "Hours" : "24/7"
    }
  ]
}

Html

<a href="#" ng-repeat="r in Restaurents.records | orderBy:'Address'" id="rest-list-f" class="offVal">
                <div class="col-md-6 col-centered form-planner-inner">
                    <span class="form-text">{{ r.Name }}</span><br>
                    <address><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span> &nbsp;{{ r.Address }}</address>
                    <img class="img-responsive" src="{{ r.Image }}" alt="{{ r.Name }} Image"><br>
                    <hr />
                    <table class="eventActive">
                        <caption><strong><center><a href="#">Click To Read Reviews</a></center></strong></caption>
                        <tr>
                            <td><span class="glyphicon glyphicon-cutlery" aria-hidden="true"></span> &nbsp;{{ r.Type }}</td>
                            <td><span class="glyphicon glyphicon-time" aria-hidden="true"></span> &nbsp;{{ r.Hours }}</td>
                        </tr>
                    </table>
                </div>
            </a>

Give it a go and feel free to group the json array while processing on the controller side.

Answer №2

If you're looking to group items in your collection using the groupBy filter from the angular.filter module, you can easily achieve this by following these steps:

To use: Apply the groupBy filter to your collection and specify the property you want to group by. You can also use dot notation for nested properties, like property.nested_property.

Example in JavaScript:

$scope.players = [
  {name: 'Gene', team: 'alpha'},
  {name: 'George', team: 'beta'},
  {name: 'Steve', team: 'gamma'},
  {name: 'Paula', team: 'beta'},
  {name: 'Scruath', team: 'gamma'}
];

Corresponding HTML code:

<ul ng-repeat="(key, value) in players | groupBy: 'team'">
 Group name: {{ key }}
  <li ng-repeat="player in value">
   player: {{ player.name }} 
  </li>
</ul>

Expected Result:

Group name: alpha

  • player: Gene

Group name: beta

  • player: George
  • player: Paula

Group name: gamma

  • player: Steve
  • player: Scruath

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

Dealing with numerous radio buttons

Can someone assist with the issue of the "idDefault" values not changing in this scenario? <div class="form-group" > <label class="control-label">Select Colors : </label> <div ng-repeat = "color in colorlist"> <input type="radio ...

Regenerate main JavaScript files in Gulp whenever partials are edited

In my gulp task for javascript files, I included partial js files in the source and filtered them out to avoid building them unnecessarily. gulp.task("js", () => { return gulp .src([ src_js_folder + "*.js", src_js_f ...

Discover the process of creating a dynamic mailto link using AJAX and HTML

One of my tasks involves extracting email addresses from an XML document using AJAX, and then displaying them on a webpage as clickable links for sending emails. Here is a snippet of JavaScript code I am working with: emailobj = listings[i].getElementsBy ...

Currently, I am experiencing difficulties with two specific aspects of the website I am working on - the hamburger menu and the slideshow feature

I'm having trouble with the menu on my website. It's not functioning as expected - the dropdown feature isn't working, and two items are not staying in the correct position under the parent ul despite attempts to position them using CSS. Add ...

What is the process for retrieving an excel file from the backend to the frontend?

I am currently facing an issue where I want to initiate a browser download of an excel file that is generated in my backend. However, I am struggling to figure out how to pass this type of response. app.get('/all', function (req, res) { db.q ...

Encountering an error in accessing my own API: "Cannot read property 'then

I'm currently in the process of using my personal express.js API with nodejs. Although it is functioning, I am encountering an error that is preventing me from accessing the response of the request. Below is a snippet of my code: routes.js: app.post ...

The server appears to be up and running, however there seems to be an issue when attempting to access the API as it is returning an Error: connect ECONNREFUSED 127.0.0.1

Trying to decouple app and server. Successfully running, but encountering Error: connect ECONNREFUSED 127.0.0.1:3000 in Postman when hitting "app.get('/')" API despite making necessary changes. In ./routes/users.js const express = requ ...

Changing the variable within a promise in Angular 1

There seems to be an issue with updating a variable within the callback function of a promise, as shown in the code snippet below: $scope.showSelected= function (node){ var promise = $http.get("http://127.0.0.1:5000/getResource?ldpr="+nod ...

Utilizing ngClassEven and ngClassOdd in Angular 2 for Improved Styling

I attempted to replicate the behavior of ng-class-even and ng-class-odd (originally from Angular 1) in my Angular 2 application. Below is the code I wrote and it's functioning correctly, but I'm curious if there are alternative methods to achiev ...

Ways to update row background color based on specific column values

I need to customize the background color of my table rows based on the value in the "Category" column. For example: Name Category Subcategory A Paid B C Received D If the Category value is 'Paid', I want the ro ...

Guide on using Ajax to transmit data to Struts2 action class

In my Struts2 web application, I have the following files: member.jsp: <script type="text/javascript"> String str1 = "aaa"; String str2 = "bbb"; xmlhttp.open("GET", "http://localhost:8080/project/editprofile.action", true); xml ...

Vue.js problem with conditional rendering using v-if

I'm struggling to grasp the concept behind how v-if functions. My goal is to dynamically hide buttons in the navigation bar based on the user's authentication status and current page. Specifically, I want the "My Account" button to be displayed w ...

CSS swapping versus CSS altering

Looking to make changes to the CSS of a page, there are two methods that come to mind: Option 1: Utilize the Jquery .css function to modify every tag in the HTML. For instance: $("body").css("background : red") Alternatively, you can disable the current ...

Transforming the date format in VUE-JSON-EXCEL

Is there a way to change the date format for the VUE-JSON-EXCEL library? When I click the generate excel button, the date format displayed in the excel is "2022-06-10T18:18:34.000Z" instead of "10/6/2022 18:18:34" I have tried using moment.js but it is n ...

Display a message following the final ajax request made in AngularJS

I've been attempting to make multiple AJAX calls within a loop. My goal is to display a message only when the final AJAX call is successful. Can anyone provide feedback on what I might be doing incorrectly here? $scope.defer = $q.defer(); ...

How can I dictate the placement of a nested Material UI select within a popper in the DOM?

Having trouble placing a select menu in a Popper. The issue is that the nested select menu wants to mount the popup as a sibling on the body rather than a child of the popper, causing the clickaway event to fire unexpectedly. Here's the code snippet f ...

Angular allows for the creation of dynamic content, much like the append function in jQuery

I am currently working with Angular to create a dynamic star rating system. I have implemented a function to generate the code for the stars dynamically, but unfortunately, they are not showing up on the page. Can anyone help me troubleshoot this issue? B ...

What is the best way to extract a list of particular items from a nested array?

When I execute the following code: var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?"; $.getJSON(url,function(data){ $.each(data, function(i, item) { console.lo ...

AngularJS form fields dynamic validation error "Instance data is missing" on datepicker directive

In my angularjs application, I am tracking household member data and one of the crucial fields is Date of Birth (DOB). To create a custom datepicker directive, I referred to a helpful post on Stack Overflow which can be found at this link: jQuery ui datepi ...

Deactivate form fields when entering data into a set of interconnected fields

I need help with the following functionality using jQuery on the form below: 1/ If any character is entered in 'filter_loan_id', 'filter_fname', 'filter_lname', or 'filter_postcode' fields, then disable the 'fi ...