2016-03-14 56 views
1

我有一個類似於此對象的數組,移動對象數組到數組

[{ 
     name : Client 1, 
     total: 900, 
     value: 12000 
    }, { 
     name : Client 2, 
     total: 10, 
     value: 800 
    }, { 
     name : Client 3, 
     total: 5, 
     value : 0 
}] 

什麼,我想是擺脫這種3個陣列,名稱的數組,

[Client 1, Client 2, Client 3]

和陣列總計,

[900, 10, 5]

和值的數組,

[12000, 800, 0]

我想我將能夠像地圖或相似的,但我對如何使用它很迷茫。誰能幫我嗎?

回答

2

使用Array.prototype.map功能

var arr = [{ name: "Client 1", total: 900, value: 12000 }, { name: "Client 2", total: 10, value: 800 }, { name: "Client 3", total: 5, value: 0 }]; 
 

 
var totals = arr.map(e => e.total); 
 
var names = arr.map(e => e.name); 
 
var values = arr.map(e => e.value); 
 

 
document.write("<pre>" + totals + "</pre>"); 
 
document.write("<pre>" + names + "</pre>"); 
 
document.write("<pre>" + values + "</pre>");

注意從@Andy

這是ES6所以你可能需要一個transpiler如果你的瀏覽器不支持它。

+0

爲什麼'陣列#map'而不是'Array.prototype.map'? –

+0

我的意思是,爲什麼那個'#'符號? –

+1

@MatíasFidemraizer,原型簡寫,請閱讀'Array.prototype.map' –

0

您可以使用具有所需鍵的對象作爲數組。

var data = [{ name: 'Client 1', total: 900, value: 12000 }, { name: 'Client 2', total: 10, value: 800 }, { name: 'Client 3', total: 5, value: 0 }], 
 
    result = function (array) { 
 
     var r = {}; 
 
     array.forEach(function (a) { 
 
      Object.keys(a).forEach(function (k) { 
 
       r[k] = r[k] || []; 
 
       r[k].push(a[k]); 
 
      }); 
 
     }); 
 
     return r; 
 
    }(data); 
 
\t 
 
document.write('<pre>name: ' + JSON.stringify(result.name, 0, 4) + '</pre>'); 
 
document.write('<pre>total: ' + JSON.stringify(result.total, 0, 4) + '</pre>'); 
 
document.write('<pre>value: ' + JSON.stringify(result.value, 0, 4) + '</pre>'); 
 
document.write('<pre>the object: ' + JSON.stringify(result, 0, 4) + '</pre>');

0

如果我uderstood你的權利,你需要從1創建3個數組?你可以做somethink這樣的:

var names=[]; 
var totals=[]; 
var values=[]; 

for(var i=0; i<objectArray.length; i++){ 
    names.push(objectArray[i].name); 
    totals.push(objectArray[i].total); 
    values.push(objectArray[i].value); 
} 
1

如果你是罰款的物體保持每個陣列,下面Array.prototype.reduce將工作:

var a = [{ 
     name : "Client 1", 
     total: 900, 
     value: 12000 
    }, { 
     name : "Client 2", 
     total: 10, 
     value: 800 
    }, { 
     name : "Client 3", 
     total: 5, 
     value : 0 
}]; 

var res = a.reduce(function(a,b){ 
    return { 
    name: a.name.concat(b.name), 
    total: a.total.concat(b.total), 
    value: a.value.concat(b.value) 
    } 
},{ 
    name: [], 
    total:[], 
    value:[] 
}) 

console.log(res) // Object {name: Array[3], total: Array[3], value: Array[3]} 
+0

對我來說,這是最好的答案; P Reduce是從數組中產生不同結果的答案。 –