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

时间:2014-08-26 18:40:37

标签: javascript lodash

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

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

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

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:51)

您可以使用Lodash chaining ability。顾名思义,它使您能够链接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)

答案 1 :(得分:7)

_.property

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]

答案 2 :(得分:7)

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

答案 3 :(得分:0)

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

但是如果你想在方法中完成,你可以先提取所有年龄值,然后在它们上运行allpy find

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/