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

后端 未结 3 1490
长发绾君心
长发绾君心 2021-02-19 21:33

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 21:56

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

提交回复
热议问题