lodash:将数组映射到对象 [英] lodash: mapping array to object
本文介绍了lodash:将数组映射到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有内置的lodash函数来执行此操作:
Is there a built-in lodash function to take this:
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
并输出:
var output = {
foo: 'bar',
baz: 'zle'
};
现在我只是使用 Array.prototype.reduce()
:
function toHash(array, keyName, valueName) {
return array.reduce(function(dictionary, next) {
dictionary[next[keyName]] = next[valueName];
return dictionary;
}, {});
}
toHash(params, 'name', 'input');
想知道是否存在lodash捷径。
Wondering if there's a lodash short-cut.
推荐答案
lodash 4.17.2 的另一种方式
_.chain(params)
.keyBy('name')
.mapValues('input')
.value();
或
_.mapValues(_.keyBy(params, 'name'), 'input')
或 _。减少
_.reduce(
params,
(acc, { name, input }) => ({ ...acc, [name]: input }),
{}
)
这篇关于lodash:将数组映射到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文