Lodash多维采摘 [英] lodash multidimensional pluck
本文介绍了Lodash多维采摘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用lodash
库,我希望能够按照以下方式将多个值提取到多维数组中:
With the lodash
library, I'd like to be able to pluck multiple values into a multi-dimensional array, along the lines of:
var arr = [{ a: 2, b: 3, c: 4 }, { a: 1, b: 4, c: 2 }];
_.pluck(arr, ['a', 'c'])
-->
[[2, 4], [1, 2]]
这可能吗?
谢谢.
推荐答案
多个键没有拨动,但是您可以这样做:
There is no pluck on multiple keys, but you can do this:
_.map(['a', 'c'], function(path) {
return _.pluck(arr, path);
});
这将返回按键分组的值.
This will return values grouped by key.
_.mpluck = function(collection, paths) {
return _.zip(
_.map(paths, function(path) {
return _.pluck(collection, path);
})
);
}
var arr = [{ a: 2, b: 3, c: 4 }, { a: 1, b: 4, c: 2 }];
_.mpluck(arr, ['a', 'c']) --> [[2, 4], [1, 2]]
这将用指定键的数组替换每个对象.
this will replace each object by an array of the specified keys.
function mpluck(collection, paths) {
return collection.map(function(obj) {
return paths.map(function(path) {
return obj[path];
});
});
}
这篇关于Lodash多维采摘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文