在下划线js,我可以在输入后使用弹拨方法获取多列,其中方法作为linq选择投影

At underscore js, Can I get multiple columns with pluck method after input where method as linq select projection

本文关键字:方法 投影 选择 linq 我可以 js 下划线 输入 获取      更新时间:2023-09-26
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');

例如:我需要firstNameqty

要投影到多个属性,您需要 map ,而不是 采摘:

var results = _.map(
    _.where(people, {city : "ny"}), 
    function(person) {
        return { firstName: person.firstName, qty: person.qty };
    }
);

[{"firstName":"Thein","qty":5},{"firstName":"Michael","qty":3}]

(小提琴)

请注意,如果需要,可以创建一个帮助程序方法"pluckMany",该方法与使用变量参数的 ppick 执行相同的操作:

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

您可以使用 _.mixin 函数将"pluckMany"函数添加到_命名空间。 使用它你可以简单地写:

var results = _.chain(people).where({city : "ny"}).pluckMany( "firstName", "qty").value();

(小提琴)

TL;DR 使用 :

var results = _.chain(people)
    .where({ city: "ny" })
    .map(_.partialRight(_.pick, 'firstName', 'qty'))
    .value();

但是请继续阅读解释,因为我觉得找到这个解决方案的过程比实际答案更有趣。


一般模式是(它也适用于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);

如果你喜欢这种用underscorelodash编写代码的方式,我强烈建议你看看函数式编程,因为这种写作风格以及许多函数(mapreduce等等)都来自那里。

注意:这显然是下划线中的常见问题: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))

我的理解是问题的作者想要获取具有许多属性的对象数组,并将每个对象剥离为一小部分属性。

有无数种方法可以做到这一点 _ ,但我最喜欢这种方式。 传入一个空的结果对象,该对象将在函数内为"this"。 使用 _each 进行迭代,并_pick所需的字段:

var myObjects = [
    { "first" : "eric",
      "last" : "gumbo",
      "code" : "x482"
    },
    { "first" : "john",
      "last" : "dinkman",
      "code" : "y9283"
    }
];
var result = [];
_.each( myObjects, function(itm) { this.push(_.pick(itm,"first","code")) }, result );
console.log(result);

YAAUu-Yep 另一个答案使用下划线...

// use a proper browser to run this code snippet, a browser that is es6-compliant
let people = [{
    firstName: "Thein",
    city: "ny",
    qty: 5
  },
  {
    firstName: "Michael",
    city: "ny",
    qty: 3
  },
  {
    firstName: "Bloom",
    city: "nj",
    qty: 10
  }
];
// either you pick the properties you want 
let picking = _.iteratee((person) => _(person).pick("firstName", "city"));
// either you omit the properties you do not want
let omitting = _.iteratee((person) => _(person).omit("qty"));
// create the filter by city
let living = (people, city) => _(people).where({
  "city": city
});
// put the "filter by city" into a mixin (as I assume it would be used again & again)
_.mixin({
  living: living
});
// do the thing (twice), 
// these chaining methods could be done into a mixin as well
console.log("results by picking properties:", _(people).chain().living("ny").map(picking).value());
console.log("results by omitting properties:", _(people).chain().living("ny").map(omitting).value());
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

一个线性可能会节省一些行:

var results=_.pick(_.where(people, {city : "ny"}), 'firstName', 'qty');

我们不必使用采摘,省略做这个技巧。

var result = _.map(people, function(person) {
  return _.omit(person, 'city');
});