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?
Use _.filter with _.pluck
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);
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