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