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?
1
  • @Thibs => Is my answer correct for you or is it missing something? Commented Mar 7, 2018 at 18:25

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.