当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Chain + filter + value returning value is not a function?

问题描述:

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

  1. Filter the array to keep users whose selected value is true.
  2. Use 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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: