javascript - Does _.pluck preserves the original index of the "plucked" array? -


i have mongodb document array of objects field looking this:

"leaving_users" : [         {             "user_id" : "fz78pr82jpz66gc3p",             "leaving_date" : isodate("2015-06-12t14:14:14.501z")         }     ] 

can use _.pluck obtain leaving_date related specific user_id?

my code seems work fine wanted check right way it, , sure won't end different index if use _.pluck function.

here code:

if (doc.leaving_users //guarding     //if user belongs leaving_users object array     &&  _.pluck(doc.leaving_users, "user_id").indexof(userid) != -1      //if leaving_date field after yesterday     && doc.leaving_users[_.pluck(doc.leaving_users, "user_id").indexof(userid)].leaving_date > yesterday)                 {                     leftrecently  = true;                 }   else{                     leftrecently  = false;                 } 

bonus question: how make more elegant?

yes, indexes same. clear if @ the implementation of _.pluck:

_.pluck = function(obj, key) {   return _.map(obj, _.property(key)); }; 

...and 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);   (var index = 0; index < length; index++) {     var currentkey = keys ? keys[index] : index;     results[index] = iteratee(obj[currentkey], currentkey, obj);   }   return results; }; 

that said, wouldn't call _.pluck twice that, , don't think i'd use _.pluck @ all, i'd use _.findindex , save result:

var index; if (doc.leaving_users //guarding     //if user belongs leaving_users object array     && (index = _.findindex(doc.leaving_users, function(e) { e.user_id === userid; }) !== -1)     //if leaving_date field after yesterday     && doc.leaving_users[index].leaving_date > yesterday)                 {                     leftrecently  = true;                 }   else{                     leftrecently  = false;                 } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -