Edit:
I have to send multiple things in 1 big object to the server. One part of the object contains data which can be either a string or null. I want to sort my object so my Angular ng-repeat
shows the fields already filled in first, followed by the rest of the fields.
(I know I should only send the updated fields to the server by using PUT, but that's not an option right now.)
I start with a JSON object like so:
var myObject = {
14 : "a",
368 : null,
7800 : null,
3985 : "b",
522 : "c"
}
And I'd like to sort this object so that everything that isn't null comes first, like so:
{
14 : "a",
3985 : "b",
522 : "c",
368 : null,
7800 : null
}
I've found various answers here already, but none really works. I already tried something like this, but the sorting just isn't right:
var sortEmptyLast = function (a, b) {
return ((a.v.length < b.v.length) ? 1 : ((a.v.length > b.v.length) ? -1 : 0));
};
var myArray = [];
for (var key in myObject) {
var value = myObject[key] || "";
myArray.push({k: key, v: value});
}
myArray = myArray.sort(sortEmptyLast);
var sortedObject = _.zipObject(_.map(myArray, function (x) {
return [x.k, x.v];
}));
My sortedObject
will return this:
{
14 : "a",
368 : "",
522 : "c",
3985 : "b",
7800 : ""
}
I'm expecting I'm overcomplicating stuff here, so if anyone knows an easier (or at least; a working) way of doing this sorting - please enlighten me :).