Chris
Chris

Reputation: 147

Vue V-For Loop with nested Items

I'm trying to v-for an array with nested Items:

This ist the main array:

export default {
  data () {
    return {
      arr: [{
        mainId: 8,
        subItems: [{
          subId: 1,
          subSubItems: {
            subSubId: 1,
            name: 'Name1'
          }
        }]
      }, {
        mainId: 5,
        subItems: [{
          subId: 2,
          subSubItems: {
            subSubId: 3,
            name: 'Name2'
          }
        },
        {
          subId: 3,
          subSubItems: {
            subSubId: 4,
            name: 'Name3'
          }
        }]
      }]
    }
  }
 }

I've tried to loop through this array like this:

<v-card v-for="subItem in arr" :key="subItem.mainId">
                {{subItem.mainId}}
  <p v-for="subSubItem in subItem.subSubId" :key="subSubItem.subSubId"></p>
                {{subSubItem.name}}
</v-card>

But unfortunately I don't get any output: The Console Error: "Cannot read property 'subSubId' of undefined"

What mistake did I make here?

Upvotes: 0

Views: 462

Answers (2)

Nipun Jain
Nipun Jain

Reputation: 1014

Your code is correct but with some typo:

<v-card v-for="subItem in arr" :key="subItem.mainId">
  {{subItem.mainId}}
  <p v-for="subSubItem in subItem.subItems" :key="subSubItem.subId">
    {{subSubItem.subSubItems.name}}
  </p>
</v-card>

as subItem.subSubId don't event exist it have to be subItem.subItems and your are setting {{subSubItem.name}} (which don't exist either) outside <p> tag. So, I have changed your code. Hope it helps.

Upvotes: 0

Hardik Raval
Hardik Raval

Reputation: 3641

Try this:

new Vue({
    el:"#app",
    data: { 
        arr: [
        {
            mainId: 8,
            subItems: [
            {
                subId: 1,
                property: {
                    subSubId: 1,
                    name: 'Name1'
                }
            }]
        },
        {
            mainId: 5,
            subItems: [{
                subId: 2,
                    property: {
                        subSubId: 3,
                        name: 'Name2'
                    }
                },
                {
                    subId: 3,
                    property: {
                        subSubId: 4,
                        name: 'Name3'
                    }
                }
            ]
        }]    
    }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <div v-for="item in arr" :key="item.mainId">
            MainId : {{item.mainId}}
            <p v-for="subitem in item.subItems" :key="subitem.subId">
                SubItem Name : {{subitem.property.name}}
                <hr/>
            </p>
        </div>
    </div>
</body>
</html>

Upvotes: 1

Related Questions