tta*_*mpu 41 javascript underscore.js
var people = [
{firstName : "Thein", city : "ny", qty : 5},
{firstName : "Michael", city : "ny", qty : 3},
{firstName : "Bloom", city : "nj", qty : 10}
];
var results=_.pluck(_.where(people, {city : "ny"}), 'firstName');
Run Code Online (Sandbox Code Playgroud)
例如:我需要firstName和qty.
McG*_*gle 62
要投影到多个属性,您需要map,而不是采摘:
var results = _.map(
_.where(people, {city : "ny"}),
function(person) {
return { firstName: person.firstName, qty: person.qty };
}
);
Run Code Online (Sandbox Code Playgroud)
[{ "名字": "登", "数量":5},{ "名字": "迈克尔", "数量":3}]
请注意,如果您愿意,可以创建一个辅助方法"pluckMany",它与使用变量参数执行相同的操作:
// first argument is the source array, followed by one or more property names
var pluckMany = function() {
// get the property names to pluck
var source = arguments[0];
var propertiesToPluck = _.rest(arguments, 1);
return _.map(source, function(item) {
var obj = {};
_.each(propertiesToPluck, function(property) {
obj[property] = item[property];
});
return obj;
});
};
Run Code Online (Sandbox Code Playgroud)
您可以使用该_.mixin函数向_命名空间添加"pluckMany"函数.使用它你可以简单地写:
var results = _.chain(people).where({city : "ny"}).pluckMany( "firstName", "qty").value();
Run Code Online (Sandbox Code Playgroud)
nha*_*nha 17
TL; DR使用:
var results = _.chain(people)
.where({ city: "ny" })
.map(_.partialRight(_.pick, 'firstName', 'qty'))
.value();
Run Code Online (Sandbox Code Playgroud)
但请继续阅读解释,因为我觉得找到这个解决方案的过程比实际答案更有趣.
一般模式是(它也适用lodash):
_.map(array, function(obj) { return _.pick(obj, 'x', 'y', 'z'); });
鉴于这种map转换集合中每个元素的通用功能,有多种方法可以根据您的特定情况进行调整(这可以保证灵活性map,这是功能程序的一个非常基本的构建块).
让我在下面介绍几种实现我们解决方案的方法:
var _ = require('lodash'); // @lodash 2.4.1 at the time of writing
// use underscore if you want to, but please see http://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore
/* la data */
var people = [{
firstName: "Thein",
city: "ny",
qty: 5
}, {
firstName: "Michael",
city: "ny",
qty: 3
}, {
firstName: "Bloom",
city: "nj",
qty: 10
}];
/* OPTION1 : mixin' with _ */
_.mixin({
pluckMany: function() {
var array = arguments[0],
propertiesToPluck = _.rest(arguments, 1);
return _.map(array, function(item) {
/* Alternative implementation 1.1
* ------------------------------
* Taken from @mMcGarnagle answer
* _each is easy to understand here,
* but has to modify the variable `obj` from a closure
* I try to avoid that for trivial cases like this one.
*/
var obj = {};
_.each(propertiesToPluck, function(property) {
obj[property] = item[property];
});
return obj;
/* Alternative implementation 1.2
* ------------------------------
* Rewrite the previous code,
* by passing the accumulator (previously`obj`, but really it is an object that accumulates the result being constructed) across function calls.
* This construction is typical of the `reduce` function, closer to a functionnal programming style.
*/
return _.reduce(propertiesToPluck, function(obj, property) {
obj[property] = item[property];
return obj;
}, {});
/* Alternative implementation 1.3
* ------------------------------
* If we are already using lodash/underscore,
* then let's use the `pick` function ! I also included an example of `flatten` here
*/
return _.pick(item, _.flatten(propertiesToPluck, true));
/* Alternative implementation 1.4
* ------------------------------
* But really flatten is not needed.
*/
return _.partial(_.pick, item).apply(null, propertiesToPluck);
});
}
});
/* Let's use our mixed function !
* Since we call several _ functions on the same object
* it is more readable to chain the calls.
*/
var results = _.chain(people)
.where({
city: "ny"
})
.pluckMany('firstName', 'qty')
.value();
/* OPTION 2 : without mixing our code with lodash/underscore */
var results = _.chain(people)
.where({
city: "ny"
})
.map(_.partialRight(_.pick, 'firstName', 'qty'))
.value();
console.log(results);
Run Code Online (Sandbox Code Playgroud)
如果你喜欢写代码用这种方式underscore或者lodash,我强烈建议你看看函数式编程,因为这种风格写作以及许多功能(map,reduce其中包括许多其他的)从那里来的.
注意:这显然是下划线中的常见问题:https: //github.com/jashkenas/underscore/issues/1104
如果这些被排除在下划线/ lodash之外,这显然不是偶然的:"可组合性比功能更好".你也可以说do one thing and do it well.这也是为什么_.mixin存在的原因.
是的,我希望pluck可以选择传递数组,但与此同时,您可以这样做:
const pluckFields = (arr, fields) => _.map(arr, item => _.pick(item, fields))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33644 次 |
| 最近记录: |