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

后端 未结 3 746
孤街浪徒
孤街浪徒 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:10

    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);

提交回复
热议问题