最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash - How to get multiple results - Stack Overflow

programmeradmin2浏览0评论

I am using lodash. I like it.

I have a users array which looks like this:

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
}, {
    'user': 'fred',
    'age': 40,
    'active': false
}, {
    'user': 'pebbles',
    'age': 1,
    'active': true
}];

Here's how I'm finding the first user and plucking the user property:

_.result(_.find(users, 'active', false), 'user');
// 'fred'

However, I wanted to pluck the user and the age values. How can I write this?

I am using lodash. I like it.

I have a users array which looks like this:

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
}, {
    'user': 'fred',
    'age': 40,
    'active': false
}, {
    'user': 'pebbles',
    'age': 1,
    'active': true
}];

Here's how I'm finding the first user and plucking the user property:

_.result(_.find(users, 'active', false), 'user');
// 'fred'

However, I wanted to pluck the user and the age values. How can I write this?

Share Improve this question edited Jun 4, 2015 at 12:36 asked May 26, 2015 at 11:09 user4874420user4874420 4
  • 1 _.find(users, 'active', false) will return you an object, You can use it like var obj = _.find(users, 'active', false); and then get obj.user and obj.age – Satpal Commented May 26, 2015 at 11:14
  • 1 What answer do you expect? A new object with user name and age ? – vjdhama Commented May 26, 2015 at 11:16
  • 2 Yes, vjdhama new object I want – user4874420 Commented May 26, 2015 at 11:27
  • 1 Try this fiddle. – vjdhama Commented May 26, 2015 at 11:37
Add a ment  | 

2 Answers 2

Reset to default 5

If you just want to select the user and age columns from a single result you can use the pick() function like this:

_.pick(_.find(users, 'active'), ['user', 'age']);
// 'barney', 36

If you want to filter and project then you can use where() and map():

_.map(_.where(users, 'active'), _.partialRight(_.pick, ['user', 'age']));
// [{ name: 'barney', age: 36 }, { user: 'pebbles', age: 1 } ]

If you want the object user in the array and not the attribute 'user', you can get it from _.find.

_.find(users, 'active', false);
// {'user': 'fred', 'age': 40, 'active': false}
发布评论

评论列表(0)

  1. 暂无评论