Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports.

$scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... };

My challenge is sorting these items by sport name:

<ul>
  <li ng-repeat="(id, value) in sports | orderBy:'value'">
      <a ng-href='/page/{{id}}'>{{value}}</a>
  </li>
 </ul>

Unfortunately, this method doesn't seem to work as expected.

Check out the current output here

Current order:
--------------------
    Soccer // id: 1
    Tennis // id: 2
    Basketball // id: 3
    MMA // id: 4
    Street dance // id: 5
    Aerobics // id: 6
    Aerial hoop // id: 7

Desired order:
    --------------------
    Aerial hoop // id: 7
    Aerobics // id: 6
    Basketball // id: 3
    MMA // id: 4
    Soccer // id: 1
    Street dance // id: 5
    Tennis // id: 2

I attempted sorting within the controller using underscore.js but encountered issues with retaining information about ids. Link to that attempt can be found here: Attempt with Underscore.js

Can anyone provide guidance on how to effectively use `orderBy` in AngularJs when working with (key, value) pairs?

Answer №1

If you refer to the official documentation, you'll find that orderBy function in AngularJS requires an array input, not an object.

The solution involves converting your object into an array. This can be achieved using the reduce method with a custom callback function as an argument.

$scope.sports = Object.keys($scope.sports).reduce(function(arr,key){
    arr.push({id: key, value: $scope.sports[key]})
    return arr;
},[]);

Alternatively, you can utilize the map method to accomplish this transformation.

$scope.sports = Object.keys($scope.sports).map((key) => ({id: key, value: $scope.sports[key]}));

With this setup, you can now present your items sorted by the value field.

<li ng-repeat="elem in sports | orderBy:'value'">
     <a ng-href='/page/{{elem.id }}'>{{elem.value}}</a> // id: {{id}}
</li>

Here is a functional implementation:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball", 4: "MMA", 5: "Street dance", 6: "Aerobics", 7: "Aerial hoop" };
    $scope.sports = Object.keys($scope.sports).map((key) => ({id: key, value: $scope.sports[key]}));
 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="myCtrl" ng-app="myApp">
    <ul>
      <li ng-repeat="elem in sports | orderBy:'value'">
       <a ng-href='/page/{{elem.id }}'>{{elem.value}}</a> // id: {{elem.id}}
      </li>
    </ul>
</div>

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

Looking to create an Ajax Control Toolkit AutoCompleteExtender with results that are "similar"?

The Ajax AutoCompleteExtender is all set up and functioning properly, linked to a webservice that fetches results from SQL. Now, I want to enhance the user experience by providing similar results in case they can't recall the exact name of what they& ...

Show a popover within a parent div that has limited visible space due to its hidden overflow

Struggling with AngularJS, I can't seem to find a simple solution for this problem. In my code, there's a div element with the overflow: hidden property set due to an internal scrollbar. Inside this div, there's a dropdown menu that is trigg ...

Exploring the next() function in the Next JS API: A practical guide similar to Express JS

When creating an API in Next JS, I encountered an issue while passing three parameters to my API function (req, res, next). Take a look at the code snippet below: import catchAsyncErrors from "../../../middleware/catchAsyncErrors.js"; import conn ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

Tips for creating a flexible Cell component in react-big-calendar:

Is there a way to make the cell of react-big-calendar flexible depending on the number of events, and enable scrolling? Here is a screenshot showcasing my issue: https://i.stack.imgur.com/K2h69.jpg ...

Utilize Google Maps to receive directions to a specific destination and discover current traffic conditions along the route using their comprehensive API

I am currently working on implementing the Google Maps direction identifier functionality with traffic details. However, I am able to obtain directions but not specific traffic details for a selected path; it seems to apply overall traffic data instead. ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Stable and persistent popup window that remains at the forefront in a Chrome extension

Currently developing a Google Chrome extension and seeking assistance in creating a popup window that remains fixed in one corner while staying on top of all other windows. Here is a reference image for clarification: https://i.stack.imgur.com/IPw7N.jpg ...

Creating static HTML files for non-static pages using Next.js SSR/ISR

While troubleshooting an issue with a specific page, I noticed that a static HTML file was created for a non-static page using Next.js. Is this expected? The page, which we will refer to as "page1," does not include the functions getStaticPaths() or getSta ...

Navigate through FAQ items with sliders using Owl Carousel 2 - Easily switch between different chapters

Exploring the creation of a FAQ section with individual carousels for each item. My primary objective is for the carousel to transition to the next chapter when advancing beyond the last slide (backwards navigation would be a future enhancement). I'v ...

React-Tooltip trimming

Currently, I am facing a dilemma that requires some resolution. The issue at hand is related to the placement of React-Tooltip within the List element. Whenever it's positioned there, it gets clipped. On the other hand, placing it at the bottom isn&a ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Tips for retrieving the chosen value from a dropdown list in HTML

I'm having an issue with exporting specific values from multiple HTML tables into an excel file. My goal is to only export the selected values from each table, with each table being on a separate tab in the excel file. Currently, when I export the ta ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

modifying the identification value in HTML and then reverting it

Although this may seem like messy code, I'm really in need of assistance with a problem that has stumped me. Currently, I am working on an E-shop project where I have modals for displaying products. Within these modals, there is a button that allows u ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

Guide on clearing the value of the first textarea and transferring it to the second textarea using JavaScript

I have encountered an issue where the first textarea value is being copied into the second textarea because I am using the same id for the 'add more' functionality. Below is the code snippet: <div id="divShortAnswerOption_Templated"> & ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

We'll show you the steps to properly organize a set of radio buttons created dynamically within a 'controlgroup' using jQuery Mobile

I am facing an issue with grouping dynamically generated radio buttons into a jQuery Mobile control group. I generate the radio buttons and append them to a div, but they are displayed separately even though the wrapping div contains a 'controlgroup&a ...

Differences between React class properties and ES6 class properties

With React 16.2, defining class properties is done differently with the tagLine example shown below: class Header extends React.Component { tagLine = "Super Hero"; render() { .... } } Contrastingly, in ES6 classes, it's not possible to define ...