繁体   English   中英

使用lodash从数组返回对象属性

[英]return object property using lodash from array

我一直试图通过首先过滤它来返回对象的属性。 这是我做的:

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
});

它返回整个对象,因为我想返回特定属性。 任何人都可以指导我如何做到这一点?

任何帮助将不胜感激。

你可以使用Lodash 链接能力 顾名思义,它使您能够链接Lodash方法调用。 _.filter_.map在这里是合适的:

 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> 


为了记录,这是你在纯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) 

_。属性

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

_.map简写

var array = [{a: 1, b: 2}, {a: 3, b: 4}]
_.map(array, 'a') // => [1, 3]
_.result(_.find(characters, function(obj) {
       return obj.age === 40;
}), 'name');

正如elclanrs在评论中提到的,明显的解决方案只是在过滤对象后访问属性age

但是如果你想在方法中完成,你可以先提取所有年龄值,然后在其上find allpy函数:

var ageValues = _.pluck(characters, 'age'); //returns [36, 40, 1]

var resultAgeValue = _.find(ageValues, function(ageValue) {
   return  ageValue < 40
});

或者,链中更好的外观:

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

尝试jsFiddle: http//jsfiddle.net/pqr/j8rL780u/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM