【发布时间】:2019-07-22 15:27:53
【问题描述】:
我想为lodash repo 提供一个修复程序,但我想我应该先检查一下我没有做错什么...
当我在这个例子中使用标准 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
是我做错了什么还是没有按预期工作?
我也在 repo 中添加了这个问题,但我想我会在这里添加,因为也许我会得到更快的响应:D
【问题讨论】:
-
从未使用过 fp,但只是去了 Guide wiki 并且参数 # 不同 github.com/lodash/lodash/wiki/FP-Guide
Methods that cap iteratees to two arguments: reduce, reduceRight, & transform -
@charlietfl 是的,这就是我在代码中所做的。在原始代码中,它接受三个参数,对象、函数和累加器。在
fp代码中,它有两个参数,函数和累加器。然后它返回一个将对象作为唯一参数的函数。 -
我从中读到的是 iteratee 是变换函数......它只有 2 个参数
-
@charlietfl 哦...我现在明白了...一秒钟,需要检查一下...谢谢:D
-
可以通过使用常规函数而不是箭头函数轻松检查参数长度并检查参数数组
标签: javascript node.js lodash