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

时间:2015-08-09 01:59:00

标签: javascript

说我有一个阵列:

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

我如何获得一个对象:

{ A : 100, B : 200 }

2 个答案:

答案 0 :(得分:2)

尝试利用Array.prototype.forEach()迭代属性,数组值,将新对象的属性设置为属性,输入数组的值

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);

答案 1 :(得分:1)

看起来是使用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;