A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view?

The orderBy filter only sorts one level, but I need it to sort recursively for all children.

Input:

R2
-->S4
------>T5
------>T4
-->S3
R1
-->S2
------>T2
------>T1
-->S1

Output:

R1
-->S1
------>T1
------>T2
-->S2
R2
-->S3
------>T4
------>T5
-->S4

Please refer to the Plunker link for a live sample demonstration.

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

Answer №1

function sortNamesArray(arr){

  arr = arr.sort(function(a,b){
    return a.name > b.name;
  })

  for (var i = 0; i < arr.length; i++){
    if (arr[i].childs){
      sortNamesArray(arr[i].childs)
    }
  }
  return arr;
}
var namesArray = [
    {
        "name": "Root1",
        "Id": "2f3d17cb-d9e2-4e99-882d-546767f2765d",
        "status": "",
        "dispName": "",
        "imageURL": "",
        "childCount": "",
        "childs": [
            {
                "name": "Sub1",
                "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f98f",
                "childs": [
                    {
                        "name": "Template1",
                        "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981",
                        "status": "",
                        "dispName": "",
                        "imageURL": ""
                    },
                    {
                        "name": "Template2",
                        "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f982",
                        "status": "",
                        "dispName": "",
                        "imageURL": ""
                    }
                ]
            },
            {
                "name": "Template3",
                "Id": "ff8b3896-3b80-4e1b-be89-52a82ec9f981"

            }
        ]
    },
    {
        "name": "Root2",
        "Id": "ea0586e7-02cf-4359-94ba-8d9623590dfe",
        "childs": [
            {
                "name": "Sub2",
                "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c9",
                "childs": [
                    {
                        "name": "Template4",
                        "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c1"
                    },
                    {
                        "name": "Template5",
                        "Id": "6f1b3a60-d295-413e-92ef-1c713446e6c2"
                    }
                ]
            }
        ]
    }
];

sortNamesArray(namesArray);

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

A step-by-step guide to creating adorable rounded corners in a DIV element

I'd like to create a stylish rounded corner div on the top-right and top-left edges. I attempted it with the following code: border-top-left-radius: 5em; border-top-right-radius: 5em; Desired look of the div: https://i.stack.imgur.com/EoSvSm.jpg A ...

Secure your website with the latest JWT cookie security measures

After storing a JWT with an expiry date set 30 days ahead, the question arises - is it secure to store this JWT in a cookie? The aim is for the token to persist beyond a single session, much like the "Keep me logged in" feature found on some websites. Se ...

Fill the drop-down menu with the present day's date, month, and year

I'm new to this, so please bear with me. I have some html and jQuery code: $(document).ready(function() { var d = new Date(); var month = d.getMonth() + 1; var year = d.getFullYear(); $("#month").val(month); $("#year").val(year) ...

Utilizing jQuery in your webpack configuration for optimal performance

I encountered some issues while trying to test a simple project that involves using a jQuery function with webpack. The errors occurred during the bundling process and are as follows: ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot ...

The code functions perfectly in the Adobe Dreamweaver Preview, but unfortunately, it is not compatible with Chrome

In the process of creating a website using Adobe Dreamweaver over the past few days, I encountered an issue with JavaScript that should activate upon scrolling. Interestingly, the script works perfectly fine when accessed through this link (), but fails t ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Modifying an HTML attribute dynamically in D3 by evaluating its existing value

I'm facing a seemingly simple task, but I can't quite crack it. My web page showcases multiple bar graphs, and I'm aiming to create a button that reveals or conceals certain bars. Specifically, when toggled, I want half of the bars to vanish ...

Issues with HttpClient in C# not working with the PostAsJsonAsync method

I am currently attempting to make a call to a web API from my web application using .Net 4.5. However, as I write the code, I keep encountering an error stating that HttpClient does not have a definition for the method PostAsJsonAsync. Here is the snippet ...

Using JQuery to handle multiple JSON requests with deferred or promise methods resulted in errors

Our application allows users to load data via Ajax requests. For example, we have a selection of items known as 'tracks'. When a user clicks on a track, an Ajax request is triggered to retrieve and display the corresponding data. Each track is en ...

Find the difference between array_A and the documents in array_B using MongoDB's $match operator, and return the result as Array_C

I need to create an array_C that includes only the elements from array_A that are not present in array_B. My approach involves using $match in aggregate to specify array_B. For instance: array_A = [1, 2, 3] array_B = [2, 4, 6, 8, 10] array_C = [1, 3] I a ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

Using AJAX autocomplete with Sys.Serialization.JavaScriptSerializer

I implemented an ajax autocomplete feature in ASP.NET where a method from a web service is called to fetch postal codes. public string[] GetNames(string prefixText, int count, String contextKey) { prefixText = prefixText.Trim(); XmlNodeList list; ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...

Is your string being truncated when sending it from iOS to a web server using POST?

Recently, I encountered an issue while attempting to send a serialized object from my iOS app to a web server. Everything seemed to be working fine when sending a large string, but as soon as I tried sending the serialized object, the data would get cut of ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

Validation using Joi allows for a field to be optional, but if it is included, it must be a positive integer

I am facing a challenge with a field in my JOI schema that I want to make optional, allowing for both undefined and null values. However, if a value is provided, it must be a positive integer. How can I accomplish this? So far, I have attempted the follow ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

I am facing difficulties with deploying my Next.js App on Vercel. Whenever I try to deploy, I encounter an error stating that the Command "npm run build" exited with 1

Hey there! I'm currently following a tutorial by JavaScript Mastery on Next.js (big shoutout to you, sir). I've been trying to deploy it on Vercel, but running into some deployment issues and having trouble testing out different tutorials. Here&a ...

"What is the proper way to add a new row to a database utilizing AJAX and the MVC framework in C#

I am currently facing an issue with adding a new row into my database using C# MVC AJAX. Despite seeing the textbox value as a parameter in the URL, when I attempt to submit by clicking the button, it fails to work and I am unsure of how to proceed in reso ...