Tips for arranging information in ng-repeat using nested objects within JSON data on AngularJS

Looking to display an array of object properties in an Angular view. Here is the object:

$scope._Json = {
    "foo": {
        "ItemDimension1": {
            "Item": "item1",
            "ItemIndex": 1,
            "SelectedItems": [{

                "Code": "Code1" 
            }]
        }
    },
    "bar": {
        "ItemDimension2": {
            "Item": "item2",
             "ItemIndex": 3,
            "SelectedItems": [{

                "Code": "code2" 
            }]
        },
        "ItemDimension3": {
            "Item": "item3",
            "ItemIndex": 2,
            "SelectedItems": [{

                "Code": "Code3" 
            }]
        }
    },
    "Lorem": {
        "ItemDimension4": {
           "Item": "item4",
            "ItemIndex": 5,
            "SelectedItems": [{

                "Code": "Code4" 
            }]
        }
    }
  };

Desired view output should be:

item1 - 1

item3 - 2

item2 - 3

item4 - 5

However, current output is:

item4 - 5

item2 - 3

item3 - 2

item1 - 1

In the view template:

<label ng-repeat="(catagory, items) in _Json">
          <li ng-repeat="(name, itemslist) in items | orderBy:'itemslist.ItemIndex'">

              <strong>{{itemslist.Item }}</strong> - <strong>{{itemslist.ItemIndex }}</strong> 

            </li>
       </label>

How can I order this by ItemIndex?

Is there a better approach or do I need to make changes?

I have tried using orderByobject as suggested here but it didn't work.

Check out the source on Plunker:

http://plnkr.co/edit/UCnrGJjLLaEjP7K5geV0?p=preview

Answer №1

To make the built-in orderBy function work, ensure that the parameter of ng-repeat is actually an array. Check out this question for more information: sorting values of a hash object in ngRepeat - angularJS

If needed, consider using underscore.js or lodash to convert your data beforehand.

Take a look at the updated fiddle here: http://plnkr.co/edit/odMCOp65zbyfbEfmU3FX?p=preview

Add mapping to your controller (please note, this example shows top-level mapping for simplicity, refer to the updated fiddle for two-level mapping):

$scope._Json = _.map($scope._Json, function( v, k) { 
    return { key: k, value: v}      
})

Update your markup accordingly (once again, only showing top-level formatting for simplicity, check out the updated plunkr for two-level update):

<label ng-repeat="cat in _Json">
      <li ng-repeat="(name, itemslist) in cat.value | orderBy:'itemslist.ItemIndex'">        
          <strong>{{itemslist.Item }}</strong> - <strong>{{itemslist.ItemIndex }}</strong>               
      </li>
</label>

Answer №2

Here is a helpful solution:

<label ng-repeat="(category, items) in _Json">
   <li ng-repeat="(name, itemList) in items | orderBy:'itemsList.Index':true">
      <strong>{{itemList.Name}}</strong> - <strong>{{itemList.Index}}</strong> 
   </li>
</label>

Check out https://docs.angularjs.org/api/ng/filter/orderBy

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

What is the process for utilizing SWR to display information from a GraphQL Apollo Server within a NextJS application?

While I can successfully access my GraphQL query using apollo-graphql-studio, and the resolver is configured correctly, I am facing difficulty in rendering the data. Being aware of the performance benefits of swr react-hook in next-js, I intend to fetch d ...

How to append double zeros to a number in Material UI Data Grid

I'm currently working on a React.js application that utilizes the DataGrid component from the Material UI (MUI) library to display data. My challenge lies in formatting full numbers with trailing zeroes for better clarity. For example, displaying 625 ...

Making the Select Tag function as an on-click event in JQuery

So I currently have a tab set up that functions as on click links when viewed on desktop. However, for tablet and mobile devices, I need it to be transformed into a select drop down list while maintaining the same functionality. Below is the code used for ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...

Retrieve the current row by clicking the button

I've been struggling to retrieve a specific value from a row displayed on my PHP webpage. My objective is to obtain the current value from a particular cell in the row, but using getElementsByTagName has not been successful as it only returns an HTMLC ...

Exploring the utilization of functions beyond module exports

Striving to clearly communicate my intentions, please feel free to ask if anything is unclear. Within a file named www, I am configuring my socket as follows: var server = http.createServer(app); var io = require('socket.io')(server); require(& ...

The $route.reload() function seems to be ineffective in Internet Explorer

I'm currently using AngularJs to develop an application. The issue I am encountering is related to data not being refreshed in IE, even after executing the $route.reload() function. Strangely enough, this problem only occurs in Internet Explorer and w ...

Sorting and Filtering JSON Data by Value in JavaScript: A Comprehensive Guide

After successfully integrating the Star Wars API to show character names from the "people" object in this JSON array retrieved from , I now need to filter the results based on a specific value which corresponds to . The current code displays all species of ...

Having trouble locating an element, Sammy?

I am encountering an issue while using Sammy for my SPA. The error message I receive is: [Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get / Error: 404 Not Found get / at Sammy.Application.error (sammy-latest ...

Save the output of a knex query to a variable

I'm struggling to assign the result of a select query using Knexjs to a variable. Here is my code: function getAllCategories() { let categories; categories = database.from("categories").select("category").then(function (rows) { for (let row of ro ...

What is preventing unary addition from functioning in Angular?

Why isn't the += unary operator appending model data properly in this code snippet? html: <div ng-app="app"> <div ng-controller="con1"> <input ng-model="mydata"/> <br/> {{ mydata }} </div> </div> an ...

`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, du ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

How to use Nativescript to retain the keyboard visibility on Android when pressing the Enter key

When attempting to create a chat view in Nativescript Javascript, I encountered an issue. After pressing the "Send" button on the keyboard, the message is sent; however, there is a strange behavior where the first 'enter' press on the keyboard is ...

Calculating tables dynamically with jQuery

I have encountered an issue with my dynamic form/table where newly added rows are not being calculated correctly. While the static elements function as expected, the IDs and classes of the new rows do not align with the calculation logic. Can someone offe ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Having difficulty in deciding due to a response received from an ajax request

Currently, I am making an ajax request using jQuery to check the availability of a username in a database. The response from my PHP script is being successfully displayed inside a div with the ID "wnguser." However, I am facing issues when trying to use th ...

Capture a section of the body background to incorporate into the canvas space

As a newcomer to the world of canvas, I have been learning from various sources about how it works. However, my goal is more dynamic and unique than what I've seen so far. I am looking to create a body background for my webpage that is responsive, cen ...