我有一个包含一些表格数据的 JSON 提要,我正在使用 Vue.js 来显示一个 HTML 表格:
<tr v-for="row, index in content">
<td class="index" v-text="index + 1"></td>
<td v-for="column in row" v-text="column"></td>
</tr>
此提要为每一行返回一个数组,但有些行具有命名键。通过这个简单的 foreach 循环,它会忽略键,这将生成一个未以正确方式显示数据的表。
如何使用键生成表?我研究过获取 highest value from the keys并使用Array.fill()
,但我认为一定有更好的方法。
这是我的数据:
{
"content": [
[
"",
"In scope:",
"Not in scope:"
],
[
"Cars",
"",
"X"
],
[
"Bikes",
"X",
""
],
{
"0": "Houses",
"2": "X"
}
]
}
请注意,这是虚构的数据,实际数据可能会有所不同,因此我没有固定列数的解决方案。
实际输出:
| | In scope: | Not in scope: |
|--------|-----------|---------------|
| Cars | | X |
| Bikes | X | |
| Houses | X |
预期输出:
| | In scope: | Not in scope: |
|--------|-----------|---------------|
| Cars | | X |
| Bikes | X | |
| Houses | | X |
最佳答案
看起来您的第一行是标题行。如果您可以接受它作为以下项目长度的真实来源,您可以创建一个简单的函数来映射数组并为所有项目强制执行该长度。这将规范化项目,使它们成为数组,填充空洞,删除超出长度的项目,并忽略对象上的非数字键:
let o = {
"content": [
[
"",
"In scope:",
"Not in scope:"
],
[
"Cars",
"",
"X"
],
[
"Bikes",
"X",
"",
"extra data!" // < will be removed
],
{
"non number": "huh?", // < will be removef
"0": "Houses", // will fill in index 1 with undefined
"2": "X",
}
]
}
const enforceLength = (l, arr) => arr.map(arr => Array.from({length: l, ...arr}))
let l = o.content[0].length
o.content = enforceLength(l, o.content)
console.log(o.content)
如果你把它放在你的组件的一个方法中,你可以简单地在模板中调用它,比如:
<tr v-for="row, index in normalize(content)">
关于javascript - 遍历缺少元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742511/