簡體   English   中英

循環javascript中的數據

[英]Loop through data in javascript

我正在嘗試在圖表中顯示數據。 我有從我的 controller 傳遞的數據,如下所示。

0: {label: "500", backgroundColor: "rgb(102,205,170,0.5)", borderColor: "rgb(102,205,170,0.5)", data: "13,49,2,2"}
1: {label: "1000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "40,2,41,4"}
2: {label: "1500", backgroundColor: "rgb(112,128,144,0.5)", borderColor: "rgb(112,128,144,0.5)", data: "3,41,0,8"}
3: {label: "2000", backgroundColor: "rgb(220,20,60,0.5)", borderColor: "rgb(220,20,60,0.5)", data: "28,30,40,43"}
4: {label: "2500", backgroundColor: "rgb(240,230,140,0.5)", borderColor: "rgb(240,230,140,0.5)", data: "0,6,20,14"}
5: {label: "3000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "31,26,31,32"}

現在我想遍歷數據所以結果就像

label: '500',
backgroundColor: rgb(102,205,170,0.5),
borderColor: rgb(102,205,170,0.5),
data: [
    26,2,41,13
],
...

我嘗試過的如下

for (const [key, value] of Object.entries(dataChart)) {
     console.log(key.borderColor);
}

在這里我只是想顯示borderColor,但它說'未定義'

任何幫助將不勝感激。

你需要做的是value.borderColor而不是key.borderColor

當使用Object.entries並將每次迭代解構為[key, value]時, key是當前迭代的實際鍵: 0, 1, 2...value如果實際 object。

那么如果你想得到borderColor

for (const [key, value] of Object.entries(dataChart)) {
     console.log(value.borderColor); // borderColor is an attribut of value, not key
}
var entries = {
0: {label: "500", backgroundColor: "rgb(102,205,170,0.5)", borderColor: "rgb(102,205,170,0.5)", data: "13,49,2,2"},
1: {label: "1000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "40,2,41,4"},
2: {label: "1500", backgroundColor: "rgb(112,128,144,0.5)", borderColor: "rgb(112,128,144,0.5)", data: "3,41,0,8"},
3: {label: "2000", backgroundColor: "rgb(220,20,60,0.5)", borderColor: "rgb(220,20,60,0.5)", data: "28,30,40,43"},
4: {label: "2500", backgroundColor: "rgb(240,230,140,0.5)", borderColor: "rgb(240,230,140,0.5)", data: "0,6,20,14"},
5: {label: "3000", backgroundColor: "rgb(0,191,255,0.5)", borderColor: "rgb(0,191,255,0.5)", data: "31,26,31,32"}
}

for (var prop in entries)
{
    console.log(entries[prop]["data"])
}

const [key, value] of Object.entries(dataChart)您正在創建 2 個變量( keyvalue )。 這兩個變量包含數組的每個元素( value )和元素在數組中的索引( key )。 所以有時, key只是一個數字。

順便說一句,我建議使用不同的方法:

dataChart.forEach(elementOfArray => {
    console.log(elementOfArray.borderColor);
});

forEach在 js 中使用較多,它使用了回調的概念。 它將調用 function 作為參數傳遞給數組的每個元素,方法是將數組元素作為參數傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM