2

When I use the orderBy function of Lodash () it returns the array with the correct order, but changes the indexes by simple keys 0,1,2,3... I searched a little bit everywhere, but I couldn't find a solution to keep my keys.

Example :

Data :

var a = {
    "65191320": {
        "date":"20180220", 
        "comment":"Hello world"
    },
    "849165164": {
            "date":"20180221", 
            "comment":"Hello world"
        }
}

main.js :

var b = _.orderBy(a, ['date'], ['desc']);
console.log(b);

Output :

{
    0: {
        "date":"20180221", 
        "comment":"Hello world"
    },
    1: {
        "date":"20180220", 
        "comment":"Hello world"
    }
}

As you can see, the keys have been changed. Is that common ? How can I keep the keys to the index finger ? Thank you in advance.

2 Answers2

0

TL;DR: There is no way to reorder plain object properties.

Property order is not guaranteed in JavaScript objects. Only an array or a Map can guarantee that. Therefore, ordering plain object makes no sense in the first place.

Here's another answer that expands on this subject.

The orderBy() function is meant for arrays and arrays only. Underneath, it uses baseSortBy(), which looks like this:

function baseSortBy(array, comparer) {
  var length = array.length;

  array.sort(comparer);
  while (length--) {
    array[length] = array[length].value;
  }
  return array;
}

Note the while loop body: it sets array[length]. If array is an object, it will set properties to be numbers.

mingos
  • 21,858
  • 11
  • 68
  • 105
  • Okay, I understand why the indexes are being transformed ! Thank you for your answer! –  Feb 23 '18 at 15:40
0

you can solve it by doing this.

_.fromPairs(_.orderBy(_.toPairs(a), ['date'], ['desc']))

The result should be like what you expected.

Cheers.