Javascript lodash:将数组映射到对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35489849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lodash: mapping array to object
提问by core
Is there a built-in lodash function to take this:
是否有内置的 lodash 函数来执行此操作:
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
And output this:
并输出这个:
var output = {
foo: 'bar',
baz: 'zle'
};
Right now I'm just using Array.prototype.reduce()
:
现在我只是在使用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');
Wondering if there's a lodash short-cut.
想知道是否有 lodash 捷径。
回答by stasovlas
Another way with lodash 4.17.2
lodash 4.17.2 的另一种方式
_.chain(params)
.keyBy('name')
.mapValues('input')
.value();
or
或者
_.mapValues(_.keyBy(params, 'name'), 'input')
or with _.reduce
或与 _.reduce
_.reduce(
params,
(acc, { name, input }) => ({ ...acc, [name]: input }),
{}
)
回答by danday74
You should be using _.keyBy to easily convert an array to an object.
您应该使用 _.keyBy 来轻松地将数组转换为对象。
Example usage below:
下面的示例用法:
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
console.log(_.keyBy(params, 'name'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If required, you can manipulate the array before using _.keyBy or the object after using _.keyBy to get the exact desired result.
如果需要,您可以在使用 _.keyBy 之前操作数组或在使用 _.keyBy 之后操作对象以获得确切的所需结果。
回答by JagsSparrow
回答by Faisal Hasnain
You can use one liner javascript with array reducemethod and ES6 destructuringto convert array of key value pairs to object.
您可以使用一个带有数组缩减方法和ES6 解构的liner javascript将键值对数组转换为对象。
arr.reduce((map, { name, input }) => ({ ...map, [name]: input }), {});
回答by RainedColony
This seems like a job for Object.assign:
这似乎是 Object.assign 的工作:
const output = Object.assign({}, ...params.map(p => ({[p.name]: p.input})));
Edited to wrap as a function similar to OP's, this would be:
编辑以包装为类似于 OP 的函数,这将是:
const toHash = (array, keyName, valueName) =>
Object.assign({}, ...array.map(o => ({[o[keyName]]: o[valueName]})));
(Thanks to Ben Steward, good thinking...)
(感谢 Ben Steward,好主意……)
回答by djechlin
This is probably more verbose than you want, but you're asking for a slightly complex operation so actual code might be involved (the horror).
这可能比你想要的更冗长,但你要求一个稍微复杂的操作,所以可能涉及实际代码(恐怖)。
My recommendation, with zipObject
that's pretty logical:
我的建议,zipObject
这是非常合乎逻辑的:
_.zipObject(_.map(params, 'name'), _.map(params, 'input'));
Another option, more hacky, using fromPairs
:
另一种选择,更hacky,使用fromPairs
:
_.fromPairs(_.map(params, function(val) { return [val['name'], val['input']));
The anonymous function shows the hackiness -- I don't believe JS guarantees order of elements in object iteration, so callling .values()
won't do.
匿名函数显示了 hackiness - 我不相信 JS 保证对象迭代中元素的顺序,所以调用是.values()
行不通的。
回答by Zeeshan Afzal Satti
回答by Koushik Chatterjee
Another way with lodash
lodash 的另一种方式
creating pairs, and then either construct a object or ES6 Map
easily
创建对,然后构造一个对象或ES6 Map
轻松地
_(params).map(v=>[v.name, v.input]).fromPairs().value()
_(params).map(v=>[v.name, v.input]).fromPairs().value()
or
或者
_.fromPairs(params.map(v=>[v.name, v.input]))
_.fromPairs(params.map(v=>[v.name, v.input]))
Here is a working example
这是一个工作示例
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
var obj = _(params).map(v=>[v.name, v.input]).fromPairs().value();
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>