1

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 :).

Nick
  • 560
  • 6
  • 19
  • 3
    The `sortedObject` should be a list, as object properties are never sorted, but items in a list are. What would you like to achieve with the ordered properties of the `sortedObject`? – ndequeker Sep 08 '14 at 08:53
  • Objects cannot be sorted. – thefourtheye Sep 08 '14 at 08:53
  • Could you please describe the real problem you're trying to solve, not the solution you've come with that 'almost' works? ) Also, have you checked the related questions (like [this one](http://stackoverflow.com/questions/5773950/how-to-keep-an-javascript-object-array-ordered-while-also-maintaining-key-lookup), for example)? – raina77ow Sep 08 '14 at 08:55
  • Edited my question so —hopefully— you understand it better now. – Nick Sep 08 '14 at 09:25
  • As it was said, objects cannot be sorted. Keep order in array. – Albert Sadowski Sep 08 '14 at 09:27

1 Answers1

1

As said, objects do not have an explicit order. You can send the object to the server and sort the object in the view (AngularJS application in your case).

To create an ordered list from the object, with null values shown first, create a list from the object and use the AngularJS orderBy filter.

AngularJS controller:

var result = [];
var keys = _.keys(sortedObject);
angular.forEach(keys, function (key) {
    result.push(sortedObject[key]);
});
$scope.arrayFromObject = result;

AngularJS view

<span ng-repeat="item in arrayFromObject | orderBy:'name'"></span>
ndequeker
  • 7,932
  • 7
  • 61
  • 93