2015-08-09 148 views
0

反對說,我有一個數組:對象的轉換陣列鍵

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

我怎樣才能得到一個對象:

{ A : 100, B : 200 } 

回答

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

看起來像一個很大的機會無窮大到練習使用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;