David C
David C

Reputation: 979

How to convert object to Array in order using Lodash

Say I have object:

obj {
  1:{
    index: 3
  },
  2:{
    index: 1
  },
  3:{
    index: 2
  },
  4:{
    index: 0
  }
}

I want to convert it into an array but in orders of "index", so the output should be

[ { index: 0 }, { index: 1 }, { index: 2 }, { index: 3 } ]

So like _.values but ability to sort by a property?

Upvotes: 0

Views: 206

Answers (2)

Akrion
Akrion

Reputation: 18525

You really do not need a library for this since in plain JS it is practically the same with just Object.values and then sort:

const obj = { 1:{ index: 3 }, 2:{ index: 1 }, 3:{ index: 2 }, 4:{ index: 0 } }

const result = Object.values(obj).sort((a,b) => a.index - b.index)

console.log(result)

But if you really need lodash then this really is just orderby or sortBy since they work on objects with no need to do the values etc:

const obj = { 1:{ index: 3 }, 2:{ index: 1 }, 3:{ index: 2 }, 4:{ index: 0 } }

const result = _.orderBy(obj, 'index')  // or _.sortBy

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 1

jannis
jannis

Reputation: 5210

You won't find a single method to do everything you want. Instead you should divide your operation into smaller chunks and chain them. So as you wrote:

like _.values but ability to sort by a property

You write about two operations: extract values from a map (using _.values) and then sort the resulting array by a property (this can be done by _.sortBy).

To start a chain of operations in Lodash use _.chain and to materialize a chain use chain.value().

Snippet:

const obj = {
    1:{
        index: 3
    },
    2:{
        index: 1
    },
    3:{
        index: 2
    },
    4:{
        index: 0
    }
};

const result = _.chain(obj)
    .values()
    .sortBy('index')
    .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Upvotes: 1

Related Questions