return object property using lodash from array

前端 未结 4 1264
逝去的感伤
逝去的感伤 2021-01-31 19:16

I have been trying to return a property of an object by filtering it first. Here\'s what I did:

var characters = [
  { \'name\': \'barney\',  \'age\': 36, \'bloc         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 19:39

    As elclanrs mentioned in comment before obvious solution is just to access the property age after you filtered the object.

    But if you wanted to be done in method, you can first extract all age values and then allpy find function on them:

    var ageValues = _.pluck(characters, 'age'); //returns [36, 40, 1]
    
    var resultAgeValue = _.find(ageValues, function(ageValue) {
       return  ageValue < 40
    });
    

    or, better looks in chain:

    var resultAgeValue = _(characters).pluck('age').find(function(ageValue) {
       return  ageValue < 40
    });
    

    try jsFiddle: http://jsfiddle.net/pqr/j8rL780u/

提交回复
热议问题