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\'
If you look at the loadash documentation for first
. It only takes in an array as its argument, and this is probably not the API to use.
See: https://lodash.com/docs/3.10.1#first
Here is 1 method you can solve it using standard Javascript
API.
The catch here is that you can use the Object.keys(...)[index]
API to retrieve the element's key based on their position.
Then all you need to do is just loop n
number of times and using the derived key push it into another object.
var firstN = 2;
var o={a:7, b:8, c:9};
var result = {};
for (var index=0; index < firstN; index++) {
var key = Object.keys(o)[index];
result[key] = o[key];
}
console.log(result);