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.
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.
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.
Lodash's find() function returns the first element of a collection that matches the given predicate .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With