[英]Convert array of object to object with keys
说我有一个数组:
[ { name: 'A', count: 100 }, { name: 'B', count: 200 } ]
我如何获得对象:
{ A : 100, B : 200 }
尝试利用Array.prototype.forEach()
迭代属性,数组的值,将新对象的属性设置为properties,输入数组的值
var arr = [ { name: 'A', count: 100 }, { name: 'B', count: 200 } ];
// create object
var res = {};
// iterate `arr` , set property of `res` to `name` property of
// object within `arr` , set value of `res[val.name]` to value
// of property `count` within `arr`
arr.forEach(function(val, key) {
res[val.name] = val.count
});
console.log(res);
看起来像是练习Array.prototype.reduce
(或reduceRight ,具体取决于所需行为)的绝佳机会。
[{name: 'A', count: 100}, {name: 'B', count: 200}].reduceRight(
function (o, e) {o[e.name] = e.count; return o;},
{}
); // {B: 200, A: 100}
也可以轻松地将其更改为夏季,
o[e.name] = (o[e.name] || 0) + e.count;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.