Can't sort array of Javascript objects obtained via angular REST call
I ran into a rather strange problem while sorting an array of Javascript objects. I tried sorting some dummy data and it works. For some reason, I cannot sort it if I receive this object via an angular REST call.
The message looks something like this:
{
"name": "IIB",
"children": [
{
"id": "some_random_id",
"name": "Broker2",
"size": 1627,
"children": []
},
{
"id": "some_random_id",
"name": "Broker1",
"size": 203,
"children": []
}
]
}
What I want to do is sort the first level array children
based on the attribute name
.
I tried using a method sort()
for this, but for some reason it doesn't work in this case:
// restangular REST call to get that message as "data"
INode.one('topology').get().then(function(data) {
// trying 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);
});
Now if I run this code, my child array is not affected at all and it gets random every time. I also tried passing a reference to another variable and working with it, but it still doesn't work.
It works if I copy and paste the actual JSON object right into the source and then sort it.
It also works if I use 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);
}
});
I guess it has something to do with how angular parses the JSON message.
Can anyone help me with this?
source to share
Use Angular Copy API . and copy the data into the variable and try to apply the sort function to the new copied variable. It should work.
source to share