我无法正确显示json文件中的数据。数据用于一行中的单元格,每个对象是一个新行,其内部数组与该行数据相关。但是棘手的是,planID可以推断数据应该覆盖多少个单元,而不是在那里的3个单元中对数据进行硬编码。
这是json
"lorem": [
{
"name": "ipsum",
"availability": [
{
"planID": [1],
"description": "2source"
},
{
"planID": [2, 3],
"description": "Unlimited"
}
]
},
{
"name": "lorem",
"availability": [
{
"planID": [1,2,3],
"description": "check"
}
]
}
]
所以表应该看起来像
有关如何动态执行此操作的任何提示都将是惊人的。这也是一个反应项目。谢谢!
答案 0 :(得分:1)
好!遍历并生成表应如下所示:
// i create a const named json with the JSON value.
const json = {
"lorem": [{
"name": "ipsum",
"availability": [{
"planID": [1],
"description": "2source"
},
{
"planID": [2, 3],
"description": "Unlimited"
}
]
},
{
"name": "lorem",
"availability": [{
"planID": [1, 2, 3],
"description": "check"
}]
}
]
}
// get the table by id on the document
const table = document.getElementById('table');
// start iterating obj of json.lorem
for (let obj of json.lorem) {
// create tr (table row) & th (table header)
const tr = document.createElement('tr');
const th = document.createElement('th');
th.innerText = obj.name
tr.appendChild(th); // insert th into tr
// start iterating over obj.availability
for (let availability of obj.availability) {
for (let planID of availability.planID) {
//create td (table data)
const td = document.createElement('td');
td.innerText = availability.description;
tr.appendChild(td); // insert td into the tr created above
}
}
// insert the above created on each for run on the table
table.appendChild(tr);
}
console.log(table);
<table border="1" id="table">
</table>