[英]Mapping an array of objects and grouping by key in javascript
How can I succinctly achieve the following manipulation in javascript: 如何在javascript中简洁地实现以下操作:
[ {key:'a', value:1}, {key:'a', value:2}, {key:'b', value:4} ]
-> - >
{'a':[1,2], 'b':[4] }
Code simplicity is what I'm really going for and I am already using lodash but I couldn't really figure out how to do this manipulation. 我一直在追求代码简单性,并且我已经在使用lodash了,但是我真的不知道该怎么做。
Try using reduce
: 尝试使用reduce
:
var arr = [ {key:'a', value:1}, {key:'a', value:2}, {key:'b', value:4} ]; var obj = arr.reduce(function(acc, x) { if (!acc[x.key]) acc[x.key] = []; acc[x.key].push(x.value); return acc; }, {}); document.write(JSON.stringify(obj));
See MDN docs on reduce
for more information. 有关更多信息,请参见关于reduce
MDN文档 。
If you have to support IE8 or below (which doesn't have reduce
), you could use a polyfill , or you could manually loop over the array and set object keys as you go (which would look uglier). 如果必须支持IE8或更低版本(没有reduce
),则可以使用polyfill ,也可以手动循环遍历数组并随便设置对象键(看起来很丑)。 It looks like lodash also already has a reduce
function, too . 看起来lodash也已经具有reduce
功能 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.