从给定的数据结构(json 文件)我基本上需要渲染一个表。不应呈现空行和/或列。我是 JavaScript 的新手,尝试过不同的方法(转换为数组并使用 .map()、reduce()、.filter()、lodash 等)但没有成功。我什至不知道解决问题的最佳方法是什么。 (或者可能的搜索词是什么。)
“行键”(例如:mo、tu、we、th、fr)和“列键”(john、hane、doe)都不是已知的,并且可能会有所不同。
完整示例:https://jsbin.com/rafeyasena/edit?js,output
"groupA": {
"mo": { "john": 8, "jane": 5, "doe": null },
"tu": { "john": 8, "jane": 5, "doe": null },
"we": { "john": 5, "jane": 9, "doe": null },
"th": { "john": 6, "jane": 3, "doe": null },
"fr": { "john": null, "jane": null, "doe": null }
}
可能的结果数据结构
const header = ["John", "Jane"];
const content = [
"mo": {[ 8, 5 ]},
"tu": {[ 8, 5 ]},
"we": {[ 5, 9 ]},
"th": {[ 6, 3 ]}
]
预期结果(前端、React):
| John | Jane |
---|------|--------
mo | 8 | 5 |
tu | 8 | 5 |
we | 5 | 9 |
th | 6 | 3 |
到目前为止我尝试了什么: 如果它不再包含键/值 ( Delete null values in nested javascript objects ),我能够删除 null 的所有值和相应的键 - 让我面临挑战,找出所有剩余的键来构建表头。 (在下面的示例中,这将只有 John 和 Jane - 所以基本上是一种迭代所有键并记录至少存在一次的每个键的方法)。所以我目前的数据是这样的(但我不确定这是否是最好的方式):
"groupA": {
"mo": { "john": 8, "jane": 5, },
"tu": { "john": 8, "jane": 5, },
"we": { "john": 5, "jane": 9, },
"th": { "john": 6, "jane": 3, }
}
最佳答案
我只是将数据表示为二维数组(这使得渲染更容易):
const columnNames = [""];
const rows = [columnNames];
for(const [rowName, values] of Object.entries(groupA)) {
const row = [rowName];
for(const [columnName, value] of Object.entries(values)) {
let position = columnNames.indexOf(columnName);
if(value === null) continue;
if(position === -1)
position = columnNames.push(columnName) - 1;
row[position] = value;
}
rows.push(row);
}
// just some debugging:
console.log( rows.map(row => row.map(it => (it || "").padStart(10)).join("|")).join("\n") );
关于javascript - JS : Delete Object Key if all nested Values equal null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55716129/