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.