Unable to arrange an array of JavaScript objects retrieved via an Angular REST request

I'm currently encountering an unusual issue with sorting an array of JavaScript objects. While sorting some dummy data works fine, I am unable to sort the array when fetching the object through an Angular REST call.

The structure of the message is as follows:

{
    "name": "IIB",
    "children": [
        {
            "id": "some_random_id",
            "name": "Broker2",
            "size": 1627,
            "children": []
        },
        {
            "id": "some_random_id",
            "name": "Broker1",
            "size": 203,
            "children": []
        }
     ]
}

My goal is to sort the first level children array based on the name attribute.

Although I attempted to use the sort() method for this purpose, it seems to be ineffective in this scenario:

// Making a restangular REST call to retrieve the message as "data"
INode.one('topology').get().then(function(data) {

    // Attempting to sort the children array
    data.children = data.children.sort(function(a, b) {
        if (a.name > b.name) {
            return 1;
        }
        if (a.name < b.name) {
            return -1;
        }
        return 0;
    })
    console.log(data.children);

});

When executing the code, the children array remains unsorted and appears random each time. I've also tried manipulating a different variable by referencing it, but the issue persists.

Interestingly, manually pasting the JSON object directly into the source allows me to successfully sort it out.

An alternative solution involves utilizing jQuery's ajax method:

$.ajax({
    type: "GET",
    url: "same_url_angular_is_using",
    dataType: "json",
    success: function(data) {
        data.children = data.children.sort(function(a, b) {
            if (a.name > b.name) {
                return 1;
            }
            if (a.name < b.name) {
                return -1;
            }
            // a must be equal to b
            return 0;
        });

        console.log(data.children);
    },
    error: function(error) {
        console.error(error);
    }
});

It appears that the issue may be related to how Angular parses the JSON message.

If anyone could offer assistance on this matter, it would be greatly appreciated.

Answer №1

Implement the Angular copy method to duplicate the data into a new variable and then attempt to utilize the sort function on this duplicated variable. The expected outcome is successful sorting.

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

Setting dynamic routes in Next.js when the basePath is not the root can be done by carefully configuring the routing system

After following a tutorial on setting up my Next.js project to be located in a subfolder (/app), everything was running smoothly. However, I encountered issues when trying to use dynamic routes for certain pages. I attempted three different approaches: ...

Load Materialize autocomplete with data from a JSON file

After hours of research, I am struggling to populate my autocomplete input using the Materialize plugin for a website project. Since I am not well-versed in json or ajax, implementing the original example from the documentation with static data has been qu ...

PhantomJS reveals underlying jQuery bug

Currently, I am developing automated test scripts that require a headless browser (PhantomJS) to perform all DOM navigation and actions except for downloads. So, PhantomJS seems like the right choice. However, I am encountering errors when trying to use P ...

JavaScript: Transforming a key-value pair collection into an array of objects

I'm looking to convert a dictionary into a list of dictionaries using JavaScript. Can someone help me with that? var dict = { "apple" : 10, "banana" : 20, "orange" : 30 } var data = [ {"apple" : 10}, {"ban ...

Can you transform text with accents into plain ASCII characters?

I am seeking a solution in Javascript to convert accented letters and various encodings into plain English ASCII characters. The goal is to achieve the following transformations: éclair ~becomes~ eclair bär ~becomes~ bar привет ~becomes~ privet ...

Display the properties of the Json object

Within my application, I am able to display data from a JSON array which includes radio buttons for each item. What I am trying to achieve is that when a radio button is clicked, the data of that specific JSON array item will be printed in HTML format in a ...

Issues with functionality of React/NextJS audio player buttons arise following implementation of a state

I am currently customizing an Audio Player component in a NextJs application using the ReactAudioPlayer package. However, the standard Import Next/Audio and using just <Audio> without props did not yield the expected results. The player functions as ...

Posting and deleting data in AngularJS using HTTP requests

Incorporating both angularjs and c# webapi in this situation. My approach involves calling the webapi from angularjs and passing a json array. Here is the Angularjs code snippet: factory.delete = function (json) { var url = 'myUrl'; ...

A guide on looping through data in a JSON-serialized System.Data.DataTable with the help of jQuery

Here is an example of the JSON format: [ {"animal":"dog", "sound": "bark"}, {"animal":"cat", "sound": "meow"} ] I am looking to iterate over each record {...} within the brackets [ ], starting with the dog-record and then moving on to the cat- ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

"Transferring an array of data to a Laravel controller via AJAX: A step-by-step guide

Is there a way to send arrays of data to the back-end all at once? The Problem 1. This is what I'm currently sending: array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" " ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

Prohibit the emission of null values in a WebAPI OData v4 service to ensure data integrity

I am currently operating a WebAPI OData v4 service and I have a requirement to exclude null values from the output. For instance, when a User object is requested, the response includes the following information: "value": [ { "FirstName": "John", "Last ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

Tips for automatically closing one sub menu while selecting another sub menu

I am working on a code snippet to manage the menu functionality. My goal is to ensure that when I click to open one submenu, any other currently open submenus should automatically close. ;(function($) { // Ensuring everything is loaded properly $ ...

Next.js: Uh-oh! Looks like we've hit an obstacle with Error 413 Request Entity

I've encountered an issue while attempting to upload large files using Next.js. I've set up an onChange function for my file input, and here's the code snippet: const handleFileUpload = () => new Promise(async (resolve) => { if(ref ...