Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  63] [ 1]  / answers: 1 / hits: 57235  / 10 Years ago, tue, august 26, 2014, 12:00:00

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.


More From » lodash

 Answers
36

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)




[#69651] Saturday, August 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaidyn

Total Points: 633
Total Questions: 102
Total Answers: 100

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
jaidyn questions
Fri, Feb 11, 22, 00:00, 2 Years ago
Fri, May 14, 21, 00:00, 3 Years ago
Wed, Oct 30, 19, 00:00, 5 Years ago
;