简体   繁体   English

使用键将对象数组转换为对象

[英]Convert array of object to object with keys

say I have an array : 说我有一个数组:

[ { name: 'A', count: 100 }, { name: 'B', count: 200 } ]

how can I get an object : 我如何获得对象:

{ A : 100, B : 200 }

Try utilizing Array.prototype.forEach() to iterate properties , values of array , set properties of new object to properties , values of input array 尝试利用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);

Looks like a great opportunity to practice using Array.prototype.reduce (or reduceRight , depending on desired behaviour) 看起来像是练习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}

This could also be easily modified to become a summer, 也可以轻松地将其更改为夏季,

o[e.name] = (o[e.name] || 0) + e.count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM