链+过滤器+返回值不是函数
Chain + filter + value returning value is not a function?
我有下面的对象数组。数组中的每个对象都包含用户信息。
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 selectedUsers = _(usersAll)
.filter(function(u) {
return u.selected
})
.map(function(u) {
return u.name
}
.value()
但出于某种原因,它返回了这个:
类型错误:_(…).filter(…).value不是函数
我做错了什么?
将_.filter
与_.pluck
一起使用
- 筛选数组以保留
selected
值为true
的用户 - 使用
Pluck
获取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>
如果您不想使用任何库,可以使用Array#filter
和Array#map
在JavaScript中完成。
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);
使用EcmaScript 6/ES15箭头函数,可以在单行中完成
usersAll.filter(e => e.selected).map(e => e.name);
对于那些使用4.0.1
及以上版本的用户,如果使用each()
进行连锁,则可能会出现问题。检查这个https://github.com/lodash/lodash/issues/1879
问题可能类似于Uncaught TypeError: _(...).filter(...).each(...).value is not a function
解决方案是显式调用chain
方法
_.chain(usersAll) // instead of _(usersAll)
... // other chaining
.each(function(u) {
...
}
.value()
相关文章:
- 根据是否解析了 Promise 从函数返回值
- 从Ajax函数返回值
- 如何从嵌套的API函数返回值
- 从异步函数返回值
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 从节点中的回调函数返回值
- 提交时不采用函数返回值.并且没有按预期行事
- 如何从工厂传递的函数返回值
- 为什么在循环中返回时函数返回值未定义
- 从JavaScript中的嵌套函数返回值
- 存在从函数返回值的问题
- 如何从setinterval函数返回值
- javascript:从匿名函数返回值
- angularjs从html调用函数返回值
- 从命名函数返回值
- 无法从Javascript中的嵌套函数返回值
- 这是显示javascript函数返回值的最佳方式吗
- 使用ajax和回调函数向函数传递值/从函数返回值
- 构造函数中的函数返回值
- 尝试从开关语句 -JS- 中的函数返回值