我有一個 json 資料格式:
[{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
從中我生成了兩個陣列,一個用于標題列cols,另一個用于行rows
let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];
let matrix = Array(cols.length).fill(Array(rows.length).fill(0));
for(const x of notes){
let {note, subject, value} = x;
matrix[cols.indexOf(note)][rows.indexOf(subject)] = note;
}
console.log(matrix)
預期結果:
[[10,0,0],[0,0,19]]
但我的目標是將其呈現為如下所示的HTML表格:
| 主題\備注 | 注1 | 筆記2 | 注3 |
|---|---|---|---|
| 主題1 | 10 | 0 | 0 |
| 主題2 | 0 | 0 | 19 |
我怎么能這樣做,非常感謝任何建議或幫助!
uj5u.com熱心網友回復:
你在正確的軌道上。只是幾點:
- 您的意圖是宣告并創建一個 2D 陣列,但實際上并非如此
- 你有
rows并且columns混淆了 - 而不是
= note你應該有= value.
let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];
let matrix = Array(rows.length).fill().map(() => Array(cols.length).fill(0));
for(const x of notes) {
let {note, subject, value} = x;
matrix[rows.indexOf(subject)][cols.indexOf(note)] = value;
}
console.log(matrix)
uj5u.com熱心網友回復:
我可以想到幾種方法來做到這一點。一種方法是回圈cols并rows使用forEach并在其中找到匹配值notes或回傳0以構造矩陣,如下所示:
let notes = [
{'note':'n1','subject':'subject1','value':10},
{'note':'n3','subject':'subject2','value':19}
]
let cols = ['n1', 'n2', 'n3']
let rows = ['subject1', 'subject2']
let matrix = []
rows.forEach(row => {
let newRow = []
cols.forEach(col => {
newRow.push(notes.find(n => n.note === col && n.subject === row)?.value || 0)
})
matrix.push(newRow)
})
console.log(matrix)
另一種方法可能是使用reduce回圈cols并rows獲取矩陣:
let notes = [
{'note':'n1','subject':'subject1','value':10},
{'note':'n3','subject':'subject2','value':19}
]
let cols = ['n1', 'n2', 'n3']
let rows = ['subject1', 'subject2']
let matrix = rows.reduce((accRow, row) => {
accRow.push(cols.reduce((accCol, col) => {
accCol.push(notes.find(n => n.note === col && n.subject === row)?.value || 0)
return accCol
}, []))
return accRow
}, [])
console.log(matrix)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484821.html
標籤:javascript html 数组 目的
上一篇:為什么curlPOST請求回傳的結果與此CommonLibraryPOST請求到具有相同正文的相同地址的結果不同?
