使用lodash从数组返回对象属性 [英] return object property using lodash from array

查看:337
本文介绍了使用lodash从数组返回对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

您可以使用Lodash 链接能力。顾名思义,它使您能够链接Lodash方法调用。 _。过滤器 _。map 适用于此:

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>

为了记录,你可以这样做在纯JS中做:

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)

这篇关于使用lodash从数组返回对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆