【问题标题】:Chain + filter + value returning value is not a function?链+过滤+值返回值不是函数吗?
【发布时间】:2016-01-06 03:22:38
【问题描述】:

我关注对象数组。数组中的每个对象都包含用户信息。

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()

但由于某种原因,它会返回:

TypeError: _(...).filter(...).value 不是函数

我做错了什么?

【问题讨论】:

  • .value() 是什么?它可以在数组上工作
  • @Tushar 我以为是一个lodash函数来获取_chain的值?
  • 那么您想获取所有选定用户的name
  • @Tushar 不,只是selected = true 的用户数组。
  • 你不需要那个。仅使用 _.filter(usersAll, function(e) { return e.selected; }); Demo

标签: javascript underscore.js lodash


【解决方案1】:

_.filter_.pluck 一起使用

  1. 过滤数组以保留selected 值为true 的用户。
  2. 使用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#filterArray#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);

【讨论】:

  • 出于演示目的,我添加了两个selected 用户,但如果在您的情况下,如果在任何时候只能选择一个用户,您可以使用, usersAll.filter(e => e.selected)[0].name;
  • 下划线过滤器调用可以简化为_.filter(usersAll, 'selected')
  • 谢谢@GruffBunny!不知道那件事。 :)
【解决方案2】:

对于那些使用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()

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 2018-06-08
    • 2010-09-08
    • 2019-06-02
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多