Convert array of object to object with keys

后端 未结 2 1734
感动是毒
感动是毒 2021-01-26 02:15

say I have an array :

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

how can I get an object :

{ A : 100, B : 200         


        
2条回答
  •  情深已故
    2021-01-26 02:27

    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;
    

提交回复
热议问题