Ad

How To Loop Through A Sub Array In A Json Array In Vue Js?

I am having a JSON data array, I need to loop through outer as well as inner subarray and need to create a Table. Below is the sample array

    {
        class:'I',
        subDdiv:[
            {
                div: 'A',
                subjects:['Subject1','Subject2','Subject3']
            },
            {
                div: 'B',
                subjects:['Subject1','Subject2','Subject3']
            },   
        ]
}
    {
        class:'II',
        subDdiv:[
            {
                div: 'A',
                subjects:['Subject1','Subject2','Subject3']
            },
            {
                div: 'B',
                subjects:['Subject1','Subject2','Subject3']
            },   
        ]
}

Now I need to create a table with the row heading as Class and Div

labels :['class','div']

The code i written is not giving actual results,

<el-table :data="array" style="width: 100%">
  <el-table-column v-for="label in labels" :key="label"
   :prop="label"
   :label="label">
   </el-table-column>
 </el-table>

Note: i am using Element Ui Table -https://element.eleme.io/#/en-US/component/table

I need to have a table like this

I need to have a table like this

But the table I got is

enter image description here

Please help me to loop through inner subDiv and create the table. code box -https://codesandbox.io/s/vigilant-wildflower-zgiq2?file=/src/App.vue

Ad

Answer

To be able to loop the data in one loop (which is what the layout you are using require) you should flatten your data:

computed: {
    reducedArray() {
      return this.dataArray.reduce((prev, obj) => {
        let flatted = obj.subDdiv.map(item => {
          let subdiv = {};
          subdiv["class"] = obj.class;
          subdiv["div"] = item.div;
          return subdiv
        });
        return [...prev, ...flatted];
      }, []);
    }
  }

Then you can use your code as is, by looping the flatted array:

<el-table :data="reducedArray" style="width: 100%">
      <el-table-column v-for="label in labels" :key="label" :prop="label" :label="label"></el-table-column>
</el-table>
Ad
source: stackoverflow.com
Ad