我有一个 mongoDB 文档,其中包含一个对象字段数组,如下所示:
"leaving_users" : [
{
"user_id" : "FZ78Pr82JPz66Gc3p",
"leaving_date" : ISODate("2015-06-12T14:14:14.501Z")
}
]
我可以使用 _.pluck
获取与特定 user_id
相关的 leaving_date
吗?
我的代码似乎工作正常,但我想检查这是正确的方法,并确保如果我使用 _.pluck
函数。
这是我的代码:
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;
}
额外的问题:如何让它更优雅?
最佳答案
是的,索引将是相同的。如果你看一下 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
,我会用_.findIndex
并保存结果:
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;
}
关于javascript - _.pluck 是否保留了 "plucked"数组的原始索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30828502/