Lodash sorting object by values, without losing the key

You could try like this,

_.mapValues(_.invert(_.invert(obj)),parseInt);

Object {Herp: 2, Asd: 5, Foo: 8, Qwe: 12, Derp: 17}

or

var obj = {Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12}

var result = _.reduceRight(_.invert(_.invert(obj)), function(current, val, key){    
    current[key] = parseInt(val);
    return current;
},{});

Object {Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

or Using Chain methods:

_.chain(obj).invert().invert().reduceRight(function(current, val, key){ 
    current[key] = parseInt(val);
    return current;
},{}).value()

Object {Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2}

Note: It depends on browser usally object properties order is not gurrantee in most case.


This worked for me

o = _.fromPairs(_.sortBy(_.toPairs(o), 1).reverse())

Here's an example:

var o = {
  a: 2,
  c: 3,
  b: 1
};
o = _.fromPairs(_.sortBy(_.toPairs(o), 1).reverse())
console.log(o);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

I was struggling with a similar problem and I was able to solve it doing some transforms with lodash. For your problem it would be:

let doo = {Derp: 17, Herp: 2, Asd: 5, Foo: 8, Qwe: 12};

let foo = _.chain(doo)
  .map((val, key) => {
    return { name: key, count: val }
  })
  .sortBy('count')
  .reverse()
  .keyBy('name')
  .mapValues('count')
  .value();

console.log(foo);
// Derp: 17, Qwe: 12, Foo: 8, Asd: 5, Herp: 2 }