Search code examples
lodash

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?


Solution

  • 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>