How to get first n elements of an object using lodash?

后端 未结 3 792
孤街浪徒
孤街浪徒 2021-02-19 21:26

I want to get the first n key/value pairs from an object (not an array) using lodash. I found this answer for underscore, which says to use use first (doesn\'

3条回答
  •  醉话见心
    2021-02-19 22:14

    There is no straight-forward solution. Inspired by previous answers and comments, and reading a couple of articles about non-guaranteed properties order, I created a solution where I sort the keys first.

    Sorting the keys

    Here is a usable one-line approach with sorted keys (and therefore guaranteed order).

    Chaining

    _.chain(object).toPairs().sortBy(0).take(2).fromPairs().value()
    

    Without chaining

    _.fromPairs(_.take(_.sortBy(_.toPairs(object), 0), 2)),
    

    Details on sorting

    The sortBy(0) sorts our collection by keys (index 0). The original object is at first converted by toPairs() to an array of pairs (each pair is an array [key, value]) and then sorted by the first values of these pairs (the key has index 0 in the pair).


    Important: As mentioned in previous answers and comments, the order of properties cannot be guaranteed, even in the latest ES versions. See this updated SO answer. Therefore I am sorting the keys.

提交回复
热议问题