ST80
ST80

Reputation: 3903

How to loop through nested data with VueJS

In my vue-app I want to loop through han array of data which contains multiple checkboxes.

filters: [
   {
    name: "Sales & marketing",
    open: false,
    items: [
        {
            employees_cvr: {
                placeholder: "employees",
                checked: false,
                click: data => {
                    ...
                }
            },
            employees_pnr: {
                placeholder: "employees_pnr",
                checked: false,
                click: data => {
                    ...
                }
            },
            date_of_origin: {
                placeholder: "Date of origin",
                checked: false,
                click: data => {
                    console.log(data);
                }
            },
            company_search: {
                placeholder: "Search for companies",
                checked: false,
                click: data => {
                    ...
                }
            }
        }
    ]
}

now, when I do a loop like this:

<div v-for="filter in filters" :key="filter.id" class="category">
    <label @click="filter.open = !filter.open">{{filter.name}}</label>
    <div class="category__rows">
       <ul v-show="filter.open">
         <li v-for="item in filter.items" :key="item.id">
           <Checkbox v-bind:data.sync="item" />
         </li>
       </ul>
   </div>
</div>

I get the name from the object, but not the items. So when I click the label to get the state open = true, the <ul> gets visible but with no data in it.

Waht am I doing wrong and can someone help me out?

Upvotes: 0

Views: 553

Answers (1)

Yair Cohen
Yair Cohen

Reputation: 2268

You are iterating filters.items which is an array that holds one object that has multiple properties. Instead, iterate that one object.

So write this instead:

       <li v-for="item in filters.items[0]" :key="item.id">
           <Checkbox v-bind:data.sync="item" />
         </li>

This way you are actually iterating the object properties and not the array.

Upvotes: 3

Related Questions