return object property using lodash from array

早过忘川 提交于 2019-12-03 04:56:06

问题


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, 'blocked': false },
  { 'name': 'fred',    'age': 40, 'blocked': true },
  { 'name': 'pebbles', 'age': 1,  'blocked': false }
];

_.find(characters, function(chr) {
     return  chr.age == 40
});

It returns whole object where as I want to return specific property. Can anyone guide me how can I do it?

Any help will be appreciated.


回答1:


You could use the Lodash chaining ability. As its name implies, it enables you to chain Lodash methods calls. _.filter and _.map are appropriate here:

const characters = [
  { 'name': 'barney',  'age': 36, 'blocked': false },
  { 'name': 'fred',    'age': 40, 'blocked': true  },
  { 'name': 'pebbles', 'age': 1,  'blocked': false },
]

const names = _(characters)
  .filter(c => c.age < 40)
  .map('name')
  .value()

alert(names)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.min.js"></script>

For the record, this is how you can do in pure JS:

const characters = [
  { 'name': 'barney',  'age': 36, 'blocked': false },
  { 'name': 'fred',    'age': 40, 'blocked': true  },
  { 'name': 'pebbles', 'age': 1,  'blocked': false },
]

const names = characters
  .filter(c => c.age < 40)
  .map(c => c.name)

alert(names)



回答2:


_.result(_.find(characters, function(obj) {
       return obj.age === 40;
}), 'name');



回答3:


_.property

var array = [{a: 1, b: 2}, {a: 3, b: 4}]
array.map(_.property('a')) // => [1, 3]

_.map short hand

var array = [{a: 1, b: 2}, {a: 3, b: 4}]
_.map(array, 'a') // => [1, 3]



回答4:


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/



来源:https://stackoverflow.com/questions/25512955/return-object-property-using-lodash-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!