How can I get the first n (for example 3) elements of an object with underscore?
Thank you!
Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
http://underscorejs.org/#first
_.first allows you to pass a number to get the first n elements of an array.
_.first([1,2,3], 2) // [1,2]
If by object, you mean associative object, the values are not in any specified order. You could do
_.first(_.values( { 'a' : 5, 'b' : 6, 'c' : 8 }), 2) // [5,6]
but it is not guaranteed that the values you get out will be the 'first' ones, so I'm not sure when that would be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With