Steps for ordering by a JSON attribute:

Within my JSON file, I have the following simple structure:

{"Item1": {"p1": {"p1sub1": 8, "p1sub2": 7}, "p2": {"p2sub1": 6, "p2sub2": 5} }, 
"Item2": {"p1": {"p1sub1": 4, "p1sub2": 3}, "p2": {"p2sub1": 2, "p2sub2": 1} } }

To retrieve this data, I use the code below:

app.controller('customersCtrl', function($scope, $http) {
        $http.get("content2.json")
        .success(function (data) {$scope.items = data;});
});

The retrieved data is then displayed in HTML as follows:

<ul ng-repeat="(i, val) in items | orderBy:'p1.p1sub1'">
    <li>{{i}} - {{val.p1.p1sub1}} - {{val.p1.p1sub2}} - {{val.p2.p2sub1}} - {{val.p2.p2sub2}}</li>
</ul>

Regardless of what parameter is used in the "orderBy" filter, the output remains the same:

Item1 - 8 - 7 - 6 - 5
Item2 - 4 - 3 - 2 - 1

Is there a method to sort the list based on the 'p1.p1sub1' values?

Edit: My objective is to arrange the rows in ascending or descending order based on the values of p1.subp1. For example: Ascending

Item2 - 4 - 3 - 2 - 1
Item1 - 8 - 7 - 6 - 5

Descending

Item1 - 8 - 7 - 6 - 5
Item2 - 4 - 3 - 2 - 1

This is just a small preview, with the final file containing numerous items to be sorted.

Answer №1

According to @charlietfl's comments, property ordering is not preserved in Javascript/JSON objects. However, JSON does support arrays which maintain inherent ordering and indexing. Arrays are represented by comma-separated values enclosed in brackets, for example:

["StringA", "StringB", "StringC"]
creates a three-item array with the strings in that specific order.

If you have control over the JSON source, one way to achieve your desired outcome is to separate each item into its own object within an array:

[
    { 
        "name": "Item1",
        "p1": {"p1sub1": 8, "p1sub2": 7},
        "p2": {"p2sub1": 6, "p2sub2": 5},
    }, {
        "name": "Item2",
        "p1": {"p1sub1": 4, "p1sub2": 3},
        "p2": {"p2sub1": 2, "p2sub2": 1},
    }
]

(When parsing JSON from a string, note that JavaScript's JSON.parse() automatically handles arrays without any special treatment required.)

You can then utilize the existing array order or use the orderBy clause as shown in your initial attempt:

<ul ng-repeat="item in items | orderBy:'p1.p1sub1'">
    <li>{{item.name}} - {{item.p1.p1sub1}} - {{item.p1.p1sub2}} - {{item.p2.p2sub1}} - {{item.p2.p2sub2}}</li>
</ul>

If your items follow an index-based naming convention, consider removing the "name" property from the JSON and utilizing Angular's built-in $index property instead:

<ul ng-repeat="item in items | orderBy:'p1.p1sub1'">
    <li>{{'Item' + $index}} - {{item.p1.p1sub1}} - {{item.p1.p1sub2}} - {{item.p2.p2sub1}} - {{item.p2.p2sub2}}</li>
</ul>

To specify ascending/descending order, prepend the 'p1.p1sub1' in the orderBy with either a '+' or '-', such as orderBy:'-p1.p1sub1' for descending order.

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

Receiving NaN in javascript when attempting to calculate the sum using a text input field

I am trying to calculate the total value by adding a fixed price with another value entered in a text input field. Here is the HTML code snippet: <%= f.text_field :hoursclass, id:"txt_hours" %> And here is the JS code snippet: $(function() { va ...

I would love to hear your suggestions for a custom select element plugin in jQuery

After browsing multiple options online, I decided to turn to the expertise of the Stack Overflow community to ask for recommendations based on personal experience. I am specifically in search of a plugin that can substitute a select element with a custo ...

Issue: Route.get() is expecting a callback function, but instead received an undefined object in app.js

It's puzzling why this error is occurring. I have another model with a similar route and controllers, but it's not working as expected. The error message reads: Error: Route.get() requires a callback function but got a [object Undefined] at Route ...

Using Android Volley to send a POST request, you can transmit a JSON object to a Java RESTful web service

Can someone provide a concise example of how to send a JSON object in a POST request using Android Volley? Additionally, the example should demonstrate receiving data from Java Restful Webservices. ...

iPhone height is not correct

One issue I faced was when trying to view a webpage in landscape mode on iPhones (specifically testing on model SE, but it appears that many people are experiencing the same problem with other iPhone models). I have created a simple example below, consist ...

Inspecting the final element of my jQuery slider

I've been working on a jQuery slider where I add the class "currentmemory" to each child of my memory2container to show which slider is displayed. The issue arises when I reach the last slider; instead of looping back to the first one and starting ov ...

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

Unleashing the power of scroll-based dynamic pagination in ReactJS

I have 33 entries in a json format. I've implemented a code that tracks the scroll on my page and loads new 10 entries at a time. Everything works smoothly when the scroll value is set to equal or less than zero. When the scroll reaches the bottom of ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

Tips for preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

What is the process for exporting data from MongoDB?

Recently, I created a web application for fun using Handlebars, Express, and Mongoose/MongoDB. This app allows users to sign up, post advertisements for others to view and respond to. All the ads are displayed on the index page, making it a shared experie ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

What is the best way to decipher a base64 API response in AngularJs?

I'm currently facing a challenge where I have to decode the base64 encoded API response from the backend, instead of receiving it in JSON format. This is the response that I'm encountering: eyJzdGF0dXNDb2RlIjoiT0siLCJtZXNzYWdlIjoiU1VDQ0VTUyIsImR ...

Creating an interface that accurately infers the correct type based on the context

I have an example below of what I aim to achieve. My goal is to start with an empty list of DbTransactInput and then add objects to the array. I experimented with mapped types to ensure that the "Items" in the "Put" property infer the correct data type, w ...

Enhancing Watermark Functionality for Text Boxes

I am encountering an issue with three textboxes all having watermarks. When I use JavaScript to set the value of the second textbox in the OnChange event of the first textbox, the text appears as a watermark. However, when I click on the textbox, it become ...

Easily style Angular directives (whether they are custom or built-in) using the native handle for CSS

In my Angular application, I have directives set up as follows: <!doctype html> <html lang="en" ng-app="cfd"> <head> ... </head> <body> <div class="container"> <!-- Header --> <div ...

ng-if behaving unexpectedly

This is a demonstration of how I populate the Table and attach checkboxes to a controller: <tr ng-repeat="key in queryResults.userPropNames"> <td><input type="checkbox" data-ng-checked="selectedKeys.indexOf(key) != -1 ...

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...