Reputation: 55293
I've following array of objects. Each object in the array contain user information.
var usersAll = [
{ id: '1', name: 'User 1', selected: true },
{ id: '2', name: 'User 2' },
{ id: '3', name: 'User 3' },
{ id: '4', name: 'User 4' }];
I want to extract the users for whom, selected
is set to true
.
This is the code I'm using
var selectedUsers = _(usersAll)
.filter(function(u) {
return u.selected
})
.map(function(u) {
return u.name
}
.value()
But for some reason it returns this:
TypeError: _(...).filter(...).value is not a function
What am I doing wrong?
Upvotes: 3
Views: 3070
Reputation: 3244
For those using 4.0.1
and above, in case you chain with each()
, it seems there could an issue. Check this https://github.com/lodash/lodash/issues/1879
The issue may be something like Uncaught TypeError: _(...).filter(...).each(...).value is not a function
The solution would be to explicitly call the chain
method
_.chain(usersAll) // instead of _(usersAll)
... // other chaining
.each(function(u) {
...
}
.value()
Upvotes: 0
Reputation: 87203
selected
value is true
.Pluck
to get the array of values of the name
.var usersAll = [{id: '1', name: 'User 1', selected: true},
{ id: '2', name: 'User 2'},
{ id: '3', name: 'User 3'},
{ id: '4', name: 'User 4', selected: true}
];
var selectedUserNames = _.pluck(_.filter(usersAll, 'selected'), 'name');
console.log(selectedUserNames);
document.write(selectedUserNames);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
If you don't want to use any library, this can be done in JavaScript using Array#filter
and Array#map
.
var usersAll = [{id: '1', name: 'User 1', selected: true},
{ id: '2', name: 'User 2'},
{ id: '3', name: 'User 3'},
{ id: '4', name: 'User 4', selected: true}
];
var selectedUserNames = usersAll.filter(function(e) {
return e.selected;
}).map(function(e) {
return e.name;
});
console.log(selectedUserNames);
document.write(selectedUserNames);
Using EcmaScript 6/ES15 arrow function, it can be done in a single line
usersAll.filter(e => e.selected).map(e => e.name);
Upvotes: 2