Home > Software engineering >  Loop over json file to get seperate elements in my table
Loop over json file to get seperate elements in my table

Time:10-05

i'm working with BootstrapVue. I have a v-for loop which iterates over my json file and put the complete input in my <tr>-Tag.

Now I want to have an extra tr-Tag for each group in my json files - so I think I need to iterate over these groups first - but I dont know how to do that.

Code in my template:

<table>
  <tbody>
    <tr> <!-- I WANT TO ITERATE HERE OVER MY GROUPS TO SORT THEM -->
      <div v-for="(item, index) in json" :key="index">
        <b-form-input v-if="item.type" :type="item.type"></b-form-input>
      </div>
    </tr>
  </tbody>
</table>

my json:

[
    {
        "label": "Input 1",
        "type": "text",
        "group": "Test1"
    },
    {
        "label": "Input 2",
        "type": "text",
        "group": "Test2"
    },
    {
        "label": "Input 3",
        "type": "text",
        "group": "Test3"
    },
    {
        "label": "Input 4",
        "type": "number",
        "group": "Test1"
    }
]

This is what the code should look like, just for understanding, if it works:

<table>
  <tbody>
    <tr> 
       <b-form-input type="text"></b-form-input>
       <b-form-input type="number"></b-form-input>
    </tr>
    <tr>
       <b-form-input type="text"></b-form-input>
    </tr>
    <tr>
       <b-form-input type="text"></b-form-input>
    </tr>
  </tbody>
</table>

CodePudding user response:

Putting v-for for tr

<table>
  <tbody>
    <tr v-for="(group, key) in getComputedJson" :key="key">
      <div v-for="(item, indexer) in group" :key="indexer">
        <b-form-input v-if="item.type" :type="item.type"></b-form-input>
     </div>
    </tr>
  </tbody>
</table>

and define a computed handler like

<script>
export default {
 computed: {
  getComputedJson() {
   const computedJson = {};
   this.json.forEach(item => {
    if(!computedJson[item.group]) {
     computedJson[item.group] = [];
     computedJson[item.group].push({label: item.label, type: item.type});
    } else {
    computedJson[item.group].push({label: item.label, type: item.type});
   }
  }
return computedJson;
}
</script>
  • Related