我想使用 lodash 从对象(不是数组)中获取前 n 个键/值对。我找到了 this answer for underscore ,它表示使用 first(在 lodash 中不存在),或者使用 take(仅适用于数组)。
尝试从对象中获取“a:7”和“b:8”对的示例节点 session :
> 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
>
当然,肯定有一些简单的方法可以用 lodash 做到这一点,但对于我来说,我找不到任何东西。也许我必须求助于原生 js?
最佳答案
如果不编写自定义代码,则无法获取对象的前 N 个元素。这是因为有 no ordering of the elements in objects ,所以如果有一个库函数,它永远不能保证给你你期望的元素。给定一个对象,如
var obj = { b: 3, y: 2, a: 1 };
不清楚“前 2 个”指的是什么 - 您想要 a
和 b
因为这是字母顺序吗?如果是这样,它们是否按此顺序排列?如果不是,您是否需要 b
和 y
因为它们先出现?也许您想要 a
和 y
是因为它们的值最低?
除了不重复之外,无法保证您会得到什么,因此所有这些组合都是有效的。此外,您可以按任何顺序获取它们 y
和 a
是同样有效的输出您可能更喜欢一个或另一个,但它通常不会使其正确。
有很多方法可以解决这个问题,但您必须接受您需要处理非订单。
纯 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) );
这是使用 Object.keys , Array.prototype.sort , 和 Array.prototype.reduce
同样可以使用 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>
如您所见,它与以前几乎相同。执行此任务的语法和确切方法可能有所不同,但要点应该仍然存在 - 您需要排序以保持一致性,然后您可以获得任意数量的元素。
关于javascript - 如何使用 lodash 获取对象的前 n 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39483677/