1

I need to convert an object map (server response) to an array and order this by the object's key.

Given:

var ppl = {
    1: { name: 'Fred', age: 31 },
    0: { name: 'Alice', age: 33 },
    3: { name: 'Frank', age: 34 },
    2: { name: 'Mary', age: 36 }
}

console.log(ppl);

It appears that the object when created is sorted by the key, the console shows this:

{
    0: { name: 'Alice', age: 33 }
    1: { name: 'Fred', age: 31 }
    2: { name: 'Mary', age: 36 }
    3: { name: 'Frank', age: 34 }
}

Then I use lodash to convert to an array like this:

var arr = _.toArray(ppl);
console.log(arr)
  1. I don't think the order of the initial object map is guaranteed, is that correct?
  2. How can I ensure the array order is based on the object map's keys?
Thibs
  • 8,058
  • 13
  • 54
  • 85

1 Answers1

2

This is easy to do with a the _.chain() method:

var ppl = {
    1: { name: 'Fred', age: 31 },
    0: { name: 'Alice', age: 33 },
    3: { name: 'Frank', age: 34 },
    2: { name: 'Mary', age: 36 }
};

const output = _.chain(ppl)
  .toArray()
  .sortBy()
  .value();
  
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30