I have a json data format:
[{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
from that I have generate two arrays one for header column cols and other for row 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表,如下所示:

Subj\Note Note1 Note2 Note3
Subj1 10 0 0
subj2 0 0 19

我怎么能做到这一点,非常感谢您的任何建议或帮助!

推荐答案

你在正确的轨道上.只有几点:

  • 您的目的是声明并创建一个2D数组,但实际上并非如此
  • 你把rowscolumns搞混了
  • 你应该有= value个,而不是= note个.

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)

Javascript相关问答推荐

成帧器运动中的运动组件为何以收件箱开始?

过滤对象数组并动态将属性放入新数组

从mat—country—select获取整个Country数组

如何用显示网格平滑地将元素从一个地方移动到另一个地方?

防止用户在selectizeInput中取消 Select 选项

微软Edge编辑和重新发送未显示""

有没有可能使滑动img动画以更快的速度连续?

我们如何从一个行动中分派行动

v—自动完成不显示 Select 列表中的所有项目

Websocket错误—有一个或多个保留位开启:reserved1 = 1,reserved2 = 0,reserved3 = 0

可更改语言的搜索栏

从包含数百行的表中获取更改后的值(以表单形式发送到后端)的正确方法是什么?

如何在每次单击按钮时重新加载HighChart/设置HighChart动画?

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

用于在路径之间移动图像的查询

使每个<;li>;元素的 colored颜色 与随机生成的 colored颜色 列表不同(不重复

如何在独立的Angular 应用程序中添加Lucide-Angel?

P5.js中矩形内的圆弧

计算对象数组中属性的滚动增量

相对于具有选定类的不同SVG组放置自定义工具提示