Skip to content

Instantly share code, notes, and snippets.

@leocaseiro
Forked from dreadjr/example.js
Created June 8, 2016 05:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leocaseiro/c5280b7cc492da98cbc9c86d1c110fb9 to your computer and use it in GitHub Desktop.
Save leocaseiro/c5280b7cc492da98cbc9c86d1c110fb9 to your computer and use it in GitHub Desktop.
Lodash / Underscore sort object keys. Like _.sortBy(), but on keys instead of values, returning an object, not an array. Defaults to alphanumeric sort.
var obj = {b: 3, c: 2, a: 1};
_.sortKeysBy(obj);
// {a: 1, b: 3, c: 2}
_.sortKeysBy(obj, function (value, key) {
return value;
});
// {a: 1, c: 2, b: 3}
_.mixin({
'orderKeysBy': function (obj, comparator, order) {
if (_.isString(comparator) && _.isEmpty(order)) {
order = comparator;
comparator = null;
}
var keys = _.orderBy(_.keys(obj), function (key) {
return comparator ? comparator(obj[key], key) : key;
}, order);
var values = _.map(keys, function (key) {
return obj[key];
});
return _.zipObject(keys, values);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment