javascript - 如何动态循环json字符串中的所有值
问题描述
我正在 Vue.js 中创建一个项目
我需要遍历一个 JSON 对象,但不知道如何访问它。我得到了什么:
"functionality": {
"uitgifte": {
"image": "",
"value": "Handmatige capsule inname en uitgifte",
"label": "",
"splash": true,
"compare": false
},
"schakelaar": {
"image": "",
"value": "Automatische en programmeerbare aan/uit schakelaar",
"label": "",
"splash": true,
"compare": false
},
"kopjesrooster": {
"image": "",
"value": "Draaibaar kopjesrooster voor latte macchiato-glazen",
"label": "",
"splash": true,
"compare": false
},
"ontkalking": {
"image": "",
"value": "Automatische melding voor ontkalking",
"label": "",
"splash": true,
"compare": false
},
"kopgroottes": {
"image": "",
"value": "Programmeerbare kopgroottes",
"label": "",
"splash": true,
"compare": false
}
},
和html:
<div class="tab">
<table>
<tbody>
<tr>
<td>{{ main.pageCopy.functionele_specificaties }}</td>
</tr>
<tr>
<td v-for="functionality in machine.functionality.uitgifte.value" :key="functionality">{{ machine.functionality.uitgifte.value }}</td>
<td>
<img src="" alt="">
</td>
</tr>
</tbody>
</table>
</div>
说 machine.functionality.uitgifte.value 的部分我需要“uitgifte”部分是动态的,因此它循环遍历 JSON 中的所有元素。所以“uitgifte,schakelaar,kopjesrooster”等。
如果有人知道诀窍,那就太棒了。谢谢。
解决方案
您只需在更高的对象级别启动 for 循环:
<div class="tab">
<table>
<tbody>
<tr>
<td>{{ main.pageCopy.functionele_specificaties }}</td>
</tr>
<tr>
<td v-for="(functionality, index) in machine.functionality" :key="index">
{{ functionality.value }}</td>
<td>
<img src="" alt="">
</td>
</tr>
</tbody>
</table>
</div>
顺便说一句:如果您可以控制数据源,请确保为每个对象提供一个 ID,并将该 ID 用作 v-for 循环的键。