javascript - lodash/fp 转换未按预期工作

标签 javascript node.js lodash

我想为 lodash 存储库贡献一个修复程序,但我认为我应该先检查一下我是否做错了什么......

当我在此示例中使用标准 lodash 时...

const _ = require('lodash');

run = () => {
  const mapping = {
    a: 'hello',
    b: 'world'
  };

  const object = {
    a: { value: true },
    b: { value: false }
  };

  // this is the original transform function that takes three arguments...
  // 1. the object to be transformed
  // 2. the transform function
  // 3. the accumulator object
  const transformed = _.transform(
    object,
    (a, v, k, o) => { a[mapping[k]] = _.get(v, 'value'); },
    {}
  );

  console.log(transformed);
};

run();

输出是 { hello: true, world: false } 就像我预期的那样。

在上面的代码上记录 a、v、k 和 o 时,输出是...

1 a: {}
1 v: { value: true }
1 k: a
1 o: { a: { value: true }, b: { value: false } }

2 a: { hello: true }
2 v: { value: false }
2 k: b
2 o: { a: { value: true }, b: { value: false } }

但是,当我使用 lodash/fp 运行(我认为是)等效代码时...

const _ = require('lodash/fp');

run = () => {
  const mapping = {
    a: 'hello',
    b: 'world'
  };

  const object = {
    a: { value: true },
    b: { value: false }
  };

  // this is the fp transform function that takes two arguments...
  // 1. the transform function
  // 2. the accumulator object
  // it then returns a function that takes one argument...
  // 1. the object to be transformed
  const transformed = _.transform(
    (a, v, k, o) => { a[mapping[k]] = _.get('value')(v); },
    {}
  )(object);

  console.log(transformed);
};

run();

输出为{ undefined: false }。这是因为迭代器的参数似乎不正确。当我记录 a、v、k 和 o 时,我得到以下输出...

1 a: {}
1 v: { value: true }
1 k: undefined
1 o: undefined

2 a: { undefined: true }
2 v: { value: false }
2 k: undefined
2 o: undefined

我做错了什么或者这没有按预期工作吗?

我也将此作为问题添加到存储库中,但我想我应该在此处添加,因为也许我会得到更快的响应:D

https://github.com/lodash/lodash/issues/4381

最佳答案

试试这个:

const transform = _.transform.convert({ cap: false });
const transformed = transform(
  (a, v, k, o) => { a[mapping[k]] = _.get('value')(v); },
  {}
)(object);

pen

关于javascript - lodash/fp 转换未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57149231/

相关文章:

javascript - 带图像交换的 Jquery 范围 slider

javascript - Passport.js 身份验证失败时发回 JSON 响应

javascript - 使用 lodash 方法返回新形式的数组

javascript - 有没有一种方法可以在Electron中为子窗口设置属性?

javascript - 删除第一个单词 JS 之后的所有内容

javascript - 将用户从浏览器返回到 Android 应用程序

javascript - 如何在 Yeoman web 应用程序中配置 eslint?

node.js - 如何让 Express 静态文件服务器正确处理 Windows 反斜杠?

由于 lodash 合并功能,CoffesScript 中的继承无法正常工作

javascript - 使用 Lodash 使用动态和嵌套过滤条件过滤数据