javascript 下划线相当于数组的 _.pick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22280775/
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
Underscore equivalent of _.pick for arrays
提问by Mohammad Sepahvand
I understand that pick is used to get back an object with only specified properties:
我知道pick用于取回仅具有指定属性的对象:
_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
How would I perform that same operation on an array, say I have an array such as:
我将如何对数组执行相同的操作,假设我有一个数组,例如:
[{name: 'moe1', age: 50, userid: 'moe1'},
{name: 'moe2', age: 50, userid: 'moe1'},
{name: 'moe3', age: 50, userid: 'moe1'}]
and I want to map it to an array so to include only the nameand ageproperties, like:
我想将它映射到一个数组,以便只包含name和age属性,例如:
[{name: 'moe1', age: 50},
{name: 'moe2', age: 50},
{name: 'moe3', age: 50}]
Do I have to do an each()on the array then perform a pick()on each object, or is there a cleaner way?
我是否必须each()在阵列上执行一个然后pick()在每个对象上执行一个,还是有更简洁的方法?
EDIT
编辑
Sorry but just another small requirement, how would I perform a where (i.e. get all those whose age is greater than 50) and then perform the pick?
EDITgot it done like this, was unaware of how chaining works in underscore.
抱歉,只是另一个小要求,我将如何执行 where(即获取所有年龄大于 50 的人)然后执行pick?
编辑是这样完成的,不知道下划线中的链接是如何工作的。
_(data).reject(function (r) { return d.age<51; }).map(function (o) {
return _.pick(o, "age", "name");
});
回答by thefourtheye
You have to use _.mapand apply the same _.pickon all the objects.
您必须在所有对象上使用_.map和应用相同_.pick的方法。
var data = [{name: 'moe1', age: 30, userid: 'moe1'},
{name: 'moe2', age: 50, userid: 'moe1'},
{name: 'moe3', age: 60, userid: 'moe1'}];
var result = _.map(data, function(currentObject) {
return _.pick(currentObject, "name", "age");
});
console.log(result);
Output
输出
[ { name: 'moe1', age: 50 },
{ name: 'moe2', age: 50 },
{ name: 'moe3', age: 50 } ]
If you want to get the objects in which the age is > 50, you might want to do, like this
如果你想获取年龄 > 50 的对象,你可能想要这样做,像这样
var data = [{name: 'moe1', age: 30, userid: 'moe1'},
{name: 'moe2', age: 50, userid: 'moe1'},
{name: 'moe3', age: 60, userid: 'moe1'}];
function filterByAge(currentObject) {
return currentObject.age && currentObject.age > 50;
}
function omitUserId(currentObject) {
return _.omit(currentObject, "userid");
}
var result = _.map(_.filter(data, filterByAge), omitUserId);
console.log(result);
Output
输出
[ { name: 'moe3', age: 60 } ]
You can do the same with chaining, as suggested by rightfold, like this
您可以按照 rightfold 的建议对链接执行相同操作,如下所示
var result = _.chain(data).filter(filterByAge).map(omitUserId).value();

