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

What is the best location in my redux store to store my socket connection?

As a beginner in the world of Redux, I've been using slices and redux-thunks to manage my redux store. However, I've come to realize that storing my socket connection in the state is not ideal. This connection is critical across multiple componen ...

How to eliminate a particular item within a string only in rows that include a different specific item using JavaScript

Is my question clear? Here's an example to illustrate: let string = "Test text ab/c test Test t/est ### Test/ Test t/test Test test" I want to remove / only from the line that includes ###, like so: Test text ab/c test Test t/est ### Test T ...

Stopping a function that is currently running on a website using Javascript

I have a script on my website that triggers a rain feature when a user clicks on a button. However, I am struggling to figure out how to allow the user to deactivate this feature. I've tried various methods such as using break, return, and timeouts, b ...

The result of the parsing with SimpleDateFormat is null

I have a time stamp in the format "2013-03-28T15:16:58.000Z" and I need to convert it to "dd-MMM-yyyy" format. To achieve this, I wrote the following code: public static String getTime(String time) { try { String tim = time.rep ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

Retrieve the ID using AngularJS and save it to resources

As a newcomer to AngularJS, I have a query regarding saving Tasks using a resource. When the Task is saved, it correctly sends the information to the database and the server responds with the ID of the created Task after receiving the POST request. The co ...

Error in pairing AngularJS with PHP

This is my code snippet: <script> var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.get("http://ip/ss.php") .then(function (response) {$scope.names = response.data.record ...

Assistance needed in extracting the body content utilizing javascript or jquery

I am looking to swap out the body content of one page with that of another. How can I retrieve the body content from the response text of the second page in order to make this replacement? Please assist me with this. Thank you in advance, Raja ...

The best practices for integrating Firebase with REST APIs

While searching for a tutorial on integrating REST APIs with Firebase, I came across numerous code snippets utilizing the curl method calls or other helper libraries. However, what I couldn't find were the basics - such as where to call these methods ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

Generating dynamic JSON objects in Node.js

Here is the initial JSON data I have: { "fullName": "abc", "age": 19, ... } I am looking to utilize Node.js in order to add elements from the above JSON to an object called Variables within the following JSON: { &q ...

Alter a prototype method belonging to another module

If I wanted to create a custom plugin or module that alters the behavior of an object exported in another module, how can I go about modifying one of its methods? The code below illustrates my attempt at achieving this, but it seems like there may be a cru ...

Obtain the href attribute's value from an HTML document using Javascript

I'm facing an issue here. Currently, I am utilizing Grid.js (http://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/) for my project. Now, my goal is to incorporate a Lightbox with multiple thumbnails inside the dropout provide ...

Combining two functions in AngularJS

I have two factories for readability, along with one controller. I am unsure if it is feasible, but I am interested in combining the results of the two factories into one variable. code vm.result = []; vm.validate = validate; function validate(password1, ...

Is it possible to utilize Faker for generating fabricated JSON data?

Is there a method to generate fictitious data, like a name and email, and save it in a JSON file? I'm aware that faker is utilized with Node and NPM for creating fake data in JS, but can the same be done with JSON? ...

Elevate the React experience by smoothly sliding a fixed navbar upwards when scrolling down, and elegantly sliding it

tl;dr Don't miss the solution at the end! Looking to create a slide up and down effect on a fixed navbar in react? What's the best approach - using refs or the componentDidMount lifecycle hook? hideNav = (navbar) => { const hide = () ...

Setting up StrongLoop LoopBack MongoDB datasource for successful deployment on Heroku

Currently, I am utilizing LoopBack version 1.6 and have a local mongoDB server operational for development purposes with the following datasource configuration: "mongodb": { "defaultForType": "mongodb", "connector": "loopback-connector-mongodb", ...

fill collections within backbone

Looking to optimize populating a Backbone collection, I have come across the push method but it requires iterating over all items: define([ ... ], function($, _, Backbone, imagesCollection, imageTemplate, gridView) { var AppView = Backbone.View.ex ...

Breaking down numerous requests into chunks in JavaScript: A step-by-step guide

I am facing a situation where I have multiple requests to make, but they cannot all be called simultaneously. Therefore, I came up with a solution to split the set of requests into chunks of 10. I'm curious about how I can handle making these 10 reque ...

Ways to retrieve a specific Array[property] within an object?

I am struggling to access a specific property within an array of objects. My goal is to extract the "name" elements from the app catalog array, combine them with the names from the custom array apps.name, and assign the result to a new property in the ques ...