Convert array of object to object with keys

后端 未结 2 1713
感动是毒
感动是毒 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:19

    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);
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题