[英]Extract data from an array of Object
我有從數據庫中獲取的對象數組:
[對象數組] [1]
我想為每個值創建一個數組數組,但是由於我是javascript的初學者,因此無法設法找到一種方法。
例如 :
var Stats=[
[39,49,43,42,41,35], //SGW Value for each Object
[37,44,49,46,52,42], //UD Value for each Object
[8,11,8,8,16,15], //Virtual Value for each Object
...
]
目的是在chart.js上制作一個如下所示的圖表:
[圖表目標] [2]
我將需要循環數據集,因為我將添加更多數據,並且單獨設置每個數據集的時間太長了。
謝謝你的時間。
您可以這樣做:
let array1 = [ { param1: 10, param2: 20 }, { param1: 30, param2: 40 } ] let array2 = array1.map(item => Object.values(item)); console.log(array2); // prints [[10, 20], [30, 40]]
首先,您需要為要繪制的每個屬性創建一個數組; 即:
var fsp = [],
msg = [],
sgw = [];
然后,您可以遍歷數據集並將數據放入每個數組中:
yourArray.forEach(function(obj){
//obj takes the value of each object in the database
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
})
或者,如果您更熟悉for
循環
for(var obj of yourArray){
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
}
最后,您可以按照示例中的說明創建一個數組
var result = [];
result.push(fsp, msg, sgw);
結果將是
[
[89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
[77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
[24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
]
有關更多信息,請Array.forEach()
, Array.push()
和for...of
文檔
正如您在評論中指出的那樣,您可以動態生成數組,從而創建對象,例如var arrays = {};
。 然后在forEach()
,或者在for...of
,您需要使用for...in
循環遍歷對象。 您在循環頭中聲明的變量采用index的值,對於Arrays為數字,對於Objects為文字。 您必須執行以下操作:
yourArray.forEach(function(obj){
for(let index in obj){
if(!arrays[index]) // check if property has already been set and initialized
arrays[index] = []; // if not, it's initialized
arrays[index].push(obj[index]) // push the value into the array
}
})
請注意,對象已被視為數組,因為您在運行時使用填充的變量訪問其屬性。
結果將是:
arrays = {
fsp: [89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
msg: [77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
sgw: [24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
}
要僅獲取數組,請使用Object.values()
。
如果您無法想象這是如何工作的,建議您在Chrome開發者工具的控制台或Node的控制台中,或者在有實時反饋的任何地方舉一些例子,在代碼中間放置一些console.log()
變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.