Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first n elements of an object with underscore?

How can I get the first n (for example 3) elements of an object with underscore?

Thank you!

like image 774
nofear87 Avatar asked Sep 30 '14 18:09

nofear87


People also ask

How do I find the first element of an object?

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.

What is underscore function?

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

Why is _ used in JavaScript?

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.


1 Answers

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.

like image 127
ne8il Avatar answered Oct 17 '22 04:10

ne8il