我有一些需要以HTML表格形式显示的数据
Name 159 158 157
A true false false
B false true true
C true true -
var json = [{
"key1": "value1",
"tests": [{
"id": "159",
"results": [{
"name": "A",
"result": "true"
}, {
"name": "B",
"result": "false"
}, {
"name": "C",
"result": "true"
}]
},
{
"id": "158",
"results": [{
"name": "A",
"result": "false"
}, {
"name": "B",
"result": "true"
}, {
"name": "C",
"result": "true"
}]
},
{
"id": "157",
"results": [{
"name": "A",
"result": "false"
}, {
"name": "B",
"result": "true"
}]
}
]
}];
我想以上述表格的形式显示此数据。我能够获取每个单元格的列,行和值,但不知道如何将其添加到表中。
for (var i = 0; i < json[0].tests.length; i++) {
var test_json = json[0].tests[i];
var column = test_json.id;
for (var j = 0; j < test_json.results.length; j++) {
var name = test_json.results[j].name;
var result = test_json.results[j].result;
console.log('column row result :' + column, name, result);
}
}
答案 0 :(得分:0)
很尴尬,但这可行:
import React, { Component } from 'react';
class App extends Component {
render() {
var json = [
{
"key1": "value1",
"tests": [
{
"id": "159",
"results": [
{
"name": "A",
"result": "true"
},
{
"name": "B",
"result": "false"
},
{
"name": "C",
"result": "true"
}
]
},
{
"id": "158",
"results": [
{
"name": "A",
"result": "false"
},
{
"name": "B",
"result": "true"
},
{
"name": "C",
"result": "true"
}
]
},
{
"id": "157",
"results": [
{
"name": "A",
"result": "false"
},
{
"name": "B",
"result": "true"
}
]
}
]
}
];
return <table>
<tbody>
<tr>
<td>Name</td>
{json[0].tests.map(test => <td>{test.id}</td>)}
</tr>
{
["A", "B", "C"].map(test => // A, B, C
<tr>
<td>{test}</td>
{
json[0].tests.map(({results}) => // 159, 158, 157
results.filter(result => result.name === test)
.map(testname => <td>{testname.result}</td>))
}
</tr>
)
}
</tbody>
</table>
}
}
export default App;
答案 1 :(得分:0)
import React, { Component } from 'react';
class App extends Component {
render() {
var tests = {
'A': [],
'B': [],
'C': []
};
json[0].tests.map(({results, id}) =>
results.forEach(({name, result}) => tests[name][id] = result)
);
function getRow(letter) {
return (
<tr>
<td>{letter}</td>
{
json[0].tests.map(({id}) =>
tests[letter].hasOwnProperty(id)
? <td>{tests[letter][id]}</td>
: <td>-</td>
)
}
</tr>
)
}
return <table>
<tbody>
<tr>
<td>Name</td>
{json[0].tests.map(test => <td>{test.id}</td>)}
</tr>
{['A', 'B', 'C'].map(letter => getRow(letter))}
</tbody>
</table>
}
}
export default App;