Javascript 如何使用lodash获取对象的前n个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39483677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:36:58  来源:igfitidea点击:

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

javascriptunderscore.jslodash

提问by vt5491

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't exist in lodash), or to use take(only works on arrays).

我想使用 lodash从对象(不是数组)中获取前 n 个键/值对。我发现这个答案下划线,这在使用使用表示第一(在lodash不存在),或者使用(仅适用于数组)。

Sample node session trying to get the 'a:7' and 'b:8' pairs from an object:

尝试从对象中获取 'a:7' 和 'b:8' 对的示例节点会话:

> var ld=require("lodash")
undefined
> var o={a:7, b:8, c:9}
undefined
> ld.keys(o)
[ 'a', 'b', 'c' ]
> ld.take(o, 2)
[]
> ld.first(o, 2)
undefined
> 

Surely, there must be some easy way to do this with lodash, but for the life of me I can't find anything. Maybe I have to resort to native js?

当然,一定有一些简单的方法可以用 lodash 做到这一点,但对于我的生活,我找不到任何东西。也许我不得不求助于原生js?

采纳答案by VLAZ

You cannot take the first N elements of an object without writing custom code. This is because there is no ordering of the elements in objects, so if there were a library function for it, it would never be guaranteed to give you the elements you expect. Given an object like

您不能在不编写自定义代码的情况下获取对象的前 N ​​个元素。这是因为objects 中的元素没有排序,所以如果有一个库函数,它永远不会保证给你你期望的元素。给定一个对象,如

var obj = {  b: 3, y: 2, a: 1 };

it is not clear what the "first 2" refers to - do you want aand bbecause that is the alphabetic order? If so are they in that order or not? If not, do you want band ybecause they appear first? Perhaps you want aand ybecause of their values being the lowest?

不清楚“前 2”指的是什么 - 你想要吗ab因为这是字母顺序?如果是这样,它们是否按该顺序排列?如果没有,您是否想要b并且y因为它们首先出现?也许你想要a并且y因为他们的价值是最低的?

There is no guarantee for what you will get aside from not getting duplicates, so all of those combinations are valid. Furthermore, you can get them in any order yand ais equally valid output You may prefer one or another but it doesn't make it correct in general.

除了不会得到重复之外,无法保证您会得到什么,因此所有这些组合都是有效的。此外,您可以按任何顺序获取它们y并且a是同样有效的输出 您可能更喜欢一个或另一个,但通常不会使其正确。

There are ways around this and but you have to accept that you need to deal with the non-order.

有办法解决这个问题,但你必须接受你需要处理非订单。

Pure JavaScript solution.

纯 JavaScript 解决方案。

function firstN(obj, n) {
  return Object.keys(obj) //get the keys out
    .sort() //this will ensure consistent ordering of what you will get back. If you want something in non-aphabetical order, you will need to supply a custom sorting function
    .slice(0, n) //get the first N
    .reduce(function(memo, current) { //generate a new object out of them
      memo[current] = obj[current]
      return memo;
    }, {})
}
var obj = { b: 2, y: 25, a: 1 }

console.log( firstN(obj, 2) );

This is using Object.keys, Array.prototype.sort, and Array.prototype.reduce

这是使用Object.keysArray.prototype.sortArray.prototype.reduce

The same can be achieved with lodash but not vastly more concise than this - it would involve calling similar functionality. It can be done like this, for example:

使用 lodash 也可以实现相同的效果,但不会比这更简洁——它会涉及调用类似的功能。可以这样做,例如:

function firstN(obj, n) {
  return _.chain(obj)
    .keys()
    .sort()
    .take(n)
    .reduce(function(memo, current) {
      memo[current] = obj[current];
      return memo;
    }, {})
    .value();
}

var obj = { b: 2, y: 25, a: 1 }
      
console.log( firstN(obj, 2) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

As you can see, it's pretty much the same as before. There can be variations on the syntax and the exactmeans of how you do this task, but the major points should still be there - you need to sort for consistency and thenyou can get any number of items.

如您所见,它与以前几乎相同。语法和执行此任务的确切方法可能会有所不同,但要点应该仍然存在 - 您需要对一致性进行排序,然后您可以获得任意数量的项目。

回答by Samuel Toh

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.

如果您查看first. 它只接受一个数组作为其参数,这可能不是要使用的 API。

See: https://lodash.com/docs/3.10.1#first

见:https: //lodash.com/docs/3.10.1#first


Here is 1 method you can solve it using standard JavascriptAPI.


这是您可以使用标准JavascriptAPI解决它的 1 种方法。

The catch here is that you can use the Object.keys(...)[index]API to retrieve the element's key based on their position.

这里的问题是您可以使用Object.keys(...)[index]API 根据元素的位置检索元素的键。

Then all you need to do is just loop nnumber of times and using the derived key push it into another object.

然后您需要做的只是循环n次数并使用派生密钥将其推入另一个对象。

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

回答by exmaxx

There is no straight-forward solution. Inspired by previous answers and comments, and reading a couple of articles about non-guaranteed properties order, I created a solution where I sort the keys first.

没有直接的解决方案。受到之前的答案和评论的启发,并阅读了几篇关于非保证属性顺序的文章,我创建了一个解决方案,首先对键进行排序。

Sorting the keys

按键排序

Here is a usable one-line approach with sorted keys(and therefore guaranteed order).

这是一种带有排序键可用单行方法(因此有保证的顺序)。

Chaining

链接

_.chain(object).toPairs().sortBy(0).take(2).fromPairs().value()

Without chaining

无链接

_.fromPairs(_.take(_.sortBy(_.toPairs(object), 0), 2)),

Details on sorting

分拣详情

The sortBy(0)sorts our collection by keys(index 0). The original objectis at first converted by toPairs()to an array of pairs(each pairis an array [key, value]) and then sorted by the first values of these pairs(the keyhas index 0in the pair).

sortBy(0)排序由我们收集(索引0)。的原始对象首先通过转换toPairs()对的阵列(每是一个数组[key, value]),然后通过这些的第一值进行排序(在key具有索引0一对)。



Important:As mentioned in previous answers and comments, the order of properties cannot be guaranteed, even in the latest ES versions. See this updated SO answer. Therefore I am sorting the keys.

重要提示:如之前的答案和评论中所述,即使在最新的 ES 版本中,也无法保证属性的顺序。请参阅此更新的 SO 答案。因此,我正在对密钥进行排序。