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\'
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.
Here is a usable one-line approach with sorted keys (and therefore guaranteed order).
_.chain(object).toPairs().sortBy(0).take(2).fromPairs().value()
_.fromPairs(_.take(_.sortBy(_.toPairs(object), 0), 2)),
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.