_.pluck是否保留“弹拨”数组的原始索引?

时间:2015-06-14 10:54:09

标签: javascript underscore.js

我有一个mongoDB文档,其中包含一个对象数组字段,如下所示:

"leaving_users" : [
        {
            "user_id" : "FZ78Pr82JPz66Gc3p",
            "leaving_date" : ISODate("2015-06-12T14:14:14.501Z")
        }
    ]

我可以使用_.pluck获取与特定leaving_date相关的user_id吗?

我的代码似乎工作正常但我想检查这是正确的方法,并确保如果我使用_.pluck函数,我有时不会使用不同的索引。< / p>

这是我的代码:

if (doc.leaving_users //guarding
    //if the user belongs to the leaving_users object array
    &&  _.pluck(doc.leaving_users, "user_id").indexOf(userId) != -1 
    //if his leaving_date field is after yesterday
    && doc.leaving_users[_.pluck(doc.leaving_users, "user_id").indexOf(userId)].leaving_date > yesterday)
                {
                    leftRecently  = true;
                }   else{
                    leftRecently  = false;
                }

奖金问题:你怎么能让它更优雅?

1 个答案:

答案 0 :(得分:2)

是的,索引将是相同的。如果你看一下the implementation of _.pluck

,这一点很清楚
_.pluck = function(obj, key) {
  return _.map(obj, _.property(key));
};

...和the implementation of _.map

_.map = _.collect = function(obj, iteratee, context) {
  iteratee = cb(iteratee, context);
  var keys = !isArrayLike(obj) && _.keys(obj),
      length = (keys || obj).length,
      results = Array(length);
  for (var index = 0; index < length; index++) {
    var currentKey = keys ? keys[index] : index;
    results[index] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
};

那就是说,我不会那样打电话给_.pluck两次,而且我根本不认为我会_.pluck使用var index; if (doc.leaving_users //guarding //if the user belongs to the leaving_users object array && (index = _.findIndex(doc.leaving_users, function(e) { e.user_id === userId; }) !== -1) //if his leaving_date field is after yesterday && doc.leaving_users[index].leaving_date > yesterday) { leftRecently = true; } else{ leftRecently = false; } 。 d使用_.findIndex并保存结果:

script