(我找不到open Lodash Slack频道,这就是我在这里发帖的原因。)
你能否告诉我为什么fiddle中的partialRight
似乎无能为力? correctRenameKeys
函数正确地重命名了提供的object
中的键,但wrongRenameKeys
函数 - 应该完全相同 - 不会。
请在浏览器中打开JavaScript控制台,以便在运行小提琴时查看日志。我在Chrome中测试了它。
const renameKeysOfOneObject = (object, keyMappings) => {
return _.reduce(object, function(result, value, key) {
key = keyMappings[key] || key;
result[key] = value;
return result;
}, {});
};
const correctRenameKeys = (objects, keyMappings) => {
const keysRenamer = object => renameKeysOfOneObject(object, keyMappings);
return _.map(objects, keysRenamer);
};
const wrongRenameKeys = (objects, keyMappings) => {
const keysRenamer = _.partialRight(renameKeysOfOneObject, keyMappings);
return _.map(objects, keysRenamer);
};
const object = {keyToBeRenamed: 'someValue'};
const objects = [object];
const keyMapping = {keyToBeRenamed: 'newKeyName'};
const correctlyRenamed = correctRenameKeys(objects, keyMapping);
const wronglyRenamed = wrongRenameKeys(objects, keyMapping);
console.assert(_.isEqual(correctlyRenamed, wronglyRenamed),
"The two objects should be equal. " +
"The 'keyToBeRenamed' key should have been renamed to 'newKeyName'.");
console.log(correctlyRenamed);
console.log(wronglyRenamed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
答案 0 :(得分:4)
lodash文档中有两个支持声明可以回答您的问题:
除了部分应用的参数外,此方法与_.partial类似 被附加到它收到的参数。
通过运行集合中的每个元素来创建值数组 iteratee。使用三个参数调用iteratee :( value, index | key,collection)。
请注意,在lodash#map
iteratee中传递了三个参数,并且因为keyRenamer
作为iteratee传递,所以我们可以得出结论:调用签名看起来像这样:
keyRenamer(value, index, collection, keyMappings);
如果你真的希望实现部分应用函数renameKeysOfOneObject
的第二个参数的效果,那么使用lodash#partial
。
const wrongRenameKeys = (objects, keyMappings) => {
const keysRenamer = _.partial(renameKeysOfOneObject, _, keyMappings);
return _.map(objects, keysRenamer);
};
const renameKeysOfOneObject = (object, keyMappings) => {
return _.reduce(object, function(result, value, key) {
key = keyMappings[key] || key;
result[key] = value;
return result;
}, {});
};
const correctRenameKeys = (objects, keyMappings) => {
const keysRenamer = object => renameKeysOfOneObject(object, keyMappings);
return _.map(objects, keysRenamer);
};
const wrongRenameKeys = (objects, keyMappings) => {
const keysRenamer = _.partial(renameKeysOfOneObject, _, keyMappings);
return _.map(objects, keysRenamer);
};
const object = {keyToBeRenamed: 'someValue'};
const objects = [object];
const keyMapping = {keyToBeRenamed: 'newKeyName'};
const correctlyRenamed = correctRenameKeys(objects, keyMapping);
const wronglyRenamed = wrongRenameKeys(objects, keyMapping);
console.assert(_.isEqual(correctlyRenamed, wronglyRenamed),
"The two objects should be equal. " +
"The 'keyToBeRenamed' key should have been renamed to 'newKeyName'.");
console.log(correctlyRenamed);
console.log(wronglyRenamed);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>