使用lodash,为什么流程中的map方法不起作用? [英] Using lodash, why is the map method within flow not working?

查看:39
本文介绍了使用lodash,为什么流程中的map方法不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户对象,试图在其上使用lodash的 map()方法,使其仅返回userIds,同时使用 currentUserId 过滤掉所有用户.我想避免使用 chain(),因为它引入了整个库,因此似乎 flow()方法是完美的,但它没有映射到一个ID.

I have a users object am trying to use the lodash map() method on it to have it return only the userIds, while filtering out any users with the currentUserId. I wanted to avoid using chain() since it pulls in the entire library, so it seemed that the flow() method is perfect, yet it's not mapping to an array of Id's.

import {
  map, filter, flow,
} from 'lodash';

const users = {
    123: {
      uid: 123
    },
    456: {
      uid: 456
    }
};

const currentUserId = 123;

const userIds = _.flow(
  _.map(user => user.uid),
  _.filter(userId => userId !== currentUserId),
)(users);

不幸的是,这返回的对象与传递给它的对象相同.如何获得一个数组,其中包含不是当前用户的所有用户的ID?

Unfortunately, this is returning the same object as was passed into it. How can I get an array with the ids of all the users that are not the current user?

推荐答案

答案适用于lodash的标准版本.请参阅@Vlaz的答案以了解lodash的功能编程版本.

The answer applies for the standard version of lodash. Please see @Vlaz's answer for a look at the functional programming version of lodash.

当您编写 _.map(user => user.uid)时,它实际上是在调用该函数.您真正想做的是创建类似于 _.map 的函数,但是已经设置了其中一个参数.

When you write _.map(user => user.uid) it is actually invoking the function at that time. What you're really attempting to do is to create function that is similar to _.map, but has one of its arguments already set.

幸运的是,Lodash有一个内置的程序可以处理这种情况- _.partialRight

Fortunately, Lodash has a built-in to handle this situation - _.partialRight

const userIds = _.flow(
  _.partialRight(_.map, user => user.uid)
  _.partialRight(_.filter, userId => userId !== currentUserId),
)(users);

文档

或者,如果您希望使用纯JS而不是导入新函数,则只需将其包装在匿名函数中即可正确传递参数.

Alternatively if you wish to use plain JS rather than importing a new function, you can simply wrap it in an anonymous function to pass the arguments properly.

const userIds = _.flow(
  (users) => _.map(users, user => user.uid),
  (users) => _.filter(users, userId => userId !== currentUserId),
)(users);

这篇关于使用lodash,为什么流程中的map方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆