我想为 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
最佳答案
试试这个:
const transform = _.transform.convert({ cap: false });
const transformed = transform(
(a, v, k, o) => { a[mapping[k]] = _.get('value')(v); },
{}
)(object);
关于javascript - lodash/fp 转换未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57149231/