Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return object property using lodash from array

Tags:

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.

like image 831
Salman Avatar asked Aug 26 '14 18:08

Salman


People also ask

How do you check if a property exists in an object Lodash?

The _.has() method is used to check whether the path is a direct property of object or not. It returns true if path exists, else it returns false.

How do I find unique elements in an array Lodash?

Lodash has the uniq method to return unique values from an array of objects. We call map to return an array of age values from array . And then we call uniq on the returned array to get the unique values from that returned array. So we get the same result for uniques as the other examples.

What does Lodash find return?

Lodash's find() function returns the first element of a collection that matches the given predicate .

How do I get the last element of an array using Lodash?

last() method is used to get the last element of the array i.e. (n-1)th element. Parameters: This function accepts single parameter i.e. the array. Return Value: It returns the last element of the array.


1 Answers

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)
like image 135
aymericbeaumet Avatar answered Oct 05 '22 01:10

aymericbeaumet