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

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

Dealing with the percentage sign in table names during data retrieval

When using React and Express to retrieve and store data in JSON format, what is the correct way to reference tables that have a percentage sign in their name? componentDidMount() { // Retrieve data from http://localhost:5000/citystats, sort by ID, t ...

What are the steps to verify if an iframe is lacking content?

I have two different codes: one is null and the other is not null. Code with null value (== empty): <div class="col-xs-6"> <iframe style="width:868px; height:550px;" id="FileReload" src="/Account/GetPDF?NUM=101"> <html> ...

Encountering a TypeError in Material UI React Autocomplete

I tried using the demo code from here in my application, but it's not functioning as expected. I'm unsure of the differences between my code and the example on the website. The errors I'm encountering are: react-dom.development.js:14724 Unc ...

Get JSON information based on index position

Whenever I need to generate JSON data for a shopping cart, I rely on PHP's json_encode() method: { "6cb380f1bfbcd7728be7dfbf2be6bad4": { "rowid": "6cb380f1bfbcd7728be7dfbf2be6bad4", "id": "sku_131ABC", "qty": "4", "price": "35.95", ...

Challenges with encoding JSON data

This may seem like a basic issue, but I'm stuck and looking for some help. Let me explain what's going on. Here's the situation: I have a database request and I need to json encode the data retrieved from that request so I can use it in a J ...

Struggling to retrieve accurate information from JSON file in AngularJS

Having some issues with my initial AngularJS project. I am utilizing a yeoman generator and trying to fetch data from a JSON file to check the length of an array containing objects. This is contents of my data.json file: {"persons":[ { "fi ...

Is requestAnimationFrame necessary for rendering in three.js?

I am currently working on the example provided in Chapter 2 of the WebGL Up and Running book. My goal is to display a static texture-mapped cube. The initial code snippet is not functioning as expected: var camera = null, renderer = null, scene = null ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

Combining two JSON objects into a single JSON object using Python Flask

I currently have a Python Flask 3.4 web service running. In addition, I am using a MySQL database that consists of two tables - Table 1 and Table 2. For Table 1, I am able to fetch data in JSON format and display it on the browser. As for Table 2, I hav ...

Activate the opening of a .docx file in a new tab by utilizing an anchor tag

I have attached a docx file containing the terms and conditions for our project. Now, I would like to open it in a new tab. By clicking this link, you can view the <a title="click to view terms and conditions" style="color:blue;" target="_blank" href ...

Steps for allowing the cells in a Data-Table column to be edited

Is it possible to have editable cells in a column of a Data Table with the support of the plugin? ...

The alert function is not being triggered upon receiving a JSON response

I am having trouble with an alert not firing a json response. The response appears in firebug, but after upgrading from php4.4.7 to php5.3.5, I encountered this error. It could be my mistake as well. Could someone please review my code and point out where ...

Is there a way to automatically remove a document in MongoDB and Node.js once its expiration date has passed?

I'm working on an appointment booking app and I need to automatically delete booking details after the booked date has passed. How can I make this happen? I attempted to use node-scheduler for this task, but it wasn't successful. The app itself ...

Dynamically populating checkboxes and dynamically setting their checked state

I'm working with a for loop that dynamically generates 7 checkboxes in a row. Here's how it looks: @for (int i = 1; k < order.Rows.length; i++) { Row: @i <ul> @for (int j = 1; j < order.NumCheckboxes.length; j++) ...

mongodb $lookup allows for referencing multiple documents from an embedded array

My database consists of collections for boards, lists, and cards. Each board document contains an array of lists and I am working towards achieving the following desired output: { _id: 1, title: "a board", lists: [ { _i ...

Activate the toggle menu

Hi there! I'm currently working on a menu and I want the clicked item to become active, switching the active state to another item when clicked. However, my current implementation is not working as expected. Any assistance would be greatly appreciated ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

Combining a standard JSS class with Material-UI's class overrides using the classnames library

I am exploring the method of assigning multiple classes to an element in React by utilizing the classnames package from JedWatson, along with Material-UI's "overriding with classes" technique. For reference, you can see an instance in MUI's docu ...

What is the correct way to utilize the WhatsApp API for sending messages?

Trying to incorporate WhatsApp API notifications into my app has been a challenge. Despite extensive research, I have yet to find an official solution. The existence of the WhatsApp API Business is known, but it currently remains in beta and caters to com ...