InPixel
InPixel

Reputation: 67

How to dynamically loop all values in a json string

I'm creating a project in Vue.js

I need to loop through a JSON object but can't find out how to access this. what I got:

 "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
        }
    },

and the 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>

The part that says machine.functionality.uitgifte.value I need the "uitgifte" part to be dynamic so it loops through all the elements like it in the JSON. So "uitgifte, schakelaar, kopjesrooster" etc.

Would be awesome if anyone knows the trick. Thanks.

Upvotes: 0

Views: 258

Answers (1)

Bennett Dams
Bennett Dams

Reputation: 7033

You simply start your for loop at a higher object level:

<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>

BTW: If you have control of the datasource, make sure to provide an ID for each object and use that ID as the key of the v-for loop.

Upvotes: 1

Related Questions