简体   繁体   中英

JS Lodash: Sort object by value, null last

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM