What is the best way to organize JSON files data in a specific sequence?

I successfully converted 3 JSON files into an HTML page using AngularJS. Here is the code I used:

Factory code

app.factory('myapp', ['$http', function($http) {        
function getLists() {
    var tab = ['url1', 'url2', 'url3'];
    var list = [];
    for(i = 0; i < tab.length; i++) {
        $http.get(tab[i]) 
        .then(function(res) {
            list.push(res.data);
        });
    }
    return list;
}

return {
    getLists: getLists
};
]);

I aim to organize and display the data from the different files based on gender (male/female) where it depends on the 'nm' field. The names of females should appear before the names of males, with each person's data from the first URL appearing in the first line, the second URL in the second line, and so on.

Html code:

<tr ng-repeat="d in list">
  <td>{{d.nm}}</td>
  <td>{{d.cty}}</td>   
  <td>{{d.hse}}</td>
  <td>{{d.yrs}}</td> 
</tr> 

I am considering implementing a conditional test in the controller to segregate between female and male names. However, I am unsure about the exact approach. Any suggestions on how to proceed?

Answer №1

If you assign an ID to the Name field, you can then use the orderBy method to sort by the ID of the name.

<tr ng-repeat="d in list| orderBy:ID">

</tr> 

Answer №2

Angular offers an orderBy directive that can be utilized within ng-repeat to effectively sort your data.

Here is an example:

Simply replace genderField and nameField with the appropriate property names you wish to use for sorting.

<tr ng-repeat="d in list| orderBy:['genderField','nameField']">
  <td>{{d.nm}}</td>
  <td>{{d.cty}}</td>   
  <td>{{d.hse}}</td>
  <td>{{d.yrs}}</td> 
</tr> 

Reference

Answer №3

Following @tommoc’s advice from a previous comment, I successfully implemented an id and it worked like a charm :)

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

We encountered a surprise issue: "/Users/username/package.json: Unexpected character \ in JSON at index 1" – this is not a duplicate question

While running the yarn command in various projects, I encountered the same error consistently. Error message: "An unexpected error occurred: "/Users/name/package.json: Unexpected token \ in JSON at position 1". Trace: SyntaxError: /Users/name/pack ...

Error: Node.js encountered an unexpected identifier in the syntax

I'm encountering an issue with my web application. The error keeps popping up. app.get("/campground/:id/comments/new",function(req,res){ camp.findById(req.params.id)({ if(err) console.log(err); else ...

Improperly aligned rotation using tween.js and three.js

Utilizing three.js and tween.js, my goal is to develop a Rubik's cube made up of 27 small cubes grouped together for rotation by +Math.PI/2 or -Math.PI/2. To ensure smooth rotation, I am implementing the tween library. The specific issue I encounter ...

Tips for minimizing database queries for each data type

I'm currently developing an App that requires the user to input numbers into two different fields. The first field is for entering numbers, while the second field displays a calculation based on the input. Each time the user enters a number, a call to ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

Fill the next Thursday with JavaScript

I'm having trouble updating the date for the upcoming Thursday using JavaScript. The current script works fine until the end of the month, but if it's the 25th of August, the output will be "Next Thursday - 8/32/2022". I need a more intelligent s ...

Is it possible to set the state property in React js using the axios response?

After receiving data from axios, I am trying to store the response in a state value for rendering it in html. However, even though response.results displays the data when printed out, setting response.results in setState() results in an empty value. Here ...

Swap Text Inside String - JS

I have a challenge where I need to extract an ID from an HTML element and then replace part of the extracted word. For instance: HTML <input type="checkbox" id="facebookCheckbox"></div> JavaScript var x = document.getElementById("facebookCh ...

Having trouble locating the objects in the parent scope of an Angular directive

My custom directive needs to access the object $scope.$parent.users. When I use console.log $scope.$parent: myDirective.directive('scheduleItem', function(){ return { restrict: 'EA', link: function($sco ...

Having trouble with the response function not functioning properly within an AJAX autocomplete

I have implemented an autocomplete feature using the jQuery UI plugin from http://jqueryui.com/autocomplete/#remote-jsonp. $("#city" ).autocomplete({ source: function( request, response ) { $.ajax({ url: 'index.php?secController= ...

Developing a perpetually scrolling container within a webpage

I am attempting to implement a scrollable div on my webpage that can continuously load content. I am currently using the following code snippet for this --> http://jsfiddle.net/cyrus2013/Qq85d/ $(document).ready(function(){ function loadMoreContent() { ...

The seamless integration of AngularJS and the chosen library is proving to be

When I use a chosen select to load data from a JSON file in an AngularJS application, the data loads successfully with a standard HTML select. However, if I switch to using the chosen select, the data does not load. I understand that the data is fetched af ...

Childnode value getting replaced in firebase

Every time I attempt to push values to the child node, they keep getting overridden. How can I solve this issue and successfully add a new value to the child node without being overwritten? ...

How can I show a loading screen while making a synchronous AJAX call in Chrome?

Is there any method to show a loading screen in Chrome while using async:false in an AJAX call? The use of setTimeout poses several challenges when making multiple synchronous AJAX calls within the setTimeout function. Additionally, the loading indicator ...

I am experiencing an issue with environment variables not appearing in my Context component on Next.js. Should I adjust the Next.js configuration or set up the Context to properly utilize the variables?

Why are Environment Variables working on every component inside /pages but not in my Context component in Next.js? Do I need to do some configuration in Next.js for this? (Note: The Shopcontext.tsx file is using a class component that I obtained from a tu ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...