Home > Net >  How to use nested for loop in vue.js
How to use nested for loop in vue.js

Time:12-09

I have a data in following format and want to loop the data and map the data what we have inside the array.

tableEmployeeList : { 01 : { missing : [{empId: 1}]}, 02 : {missing: [{empId: 2}]}, 03: {missing : [{empId: 3}] } }

Tried using this logic but was getting an error as employee not defined

<tr v-for="employee in tableEmployeeList" :key="employee.empId">
              <tr v-for="data in employee" :key="data.empId">
                <td >{{ data.empId }}</td>
              </tr>
</tr>

CodePudding user response:

Use key employee.id Basically you can use anything as a key for example employee.name employee.age

sharing a sample of for loop in vue js

<div v-for="item in data" :key="item.id">

CodePudding user response:

It looks like the code you have written is trying to access a property called empId from the objects in the employee array, but there is no such property in the objects in your tableEmployeeList object. Instead, it looks like the objects in tableEmployeeList have properties called missing which are arrays with the IDs that you need.

To fix this issue, you could try accessing the missing property instead of the non-existent empId property in your code. For example:

<tr v-for="employee in tableEmployeeList" :key="employee">
  <tr v-for="data in employee" :key="data">
    <td >{{ data.missing }}</td>
  </tr>
</tr>

This code would iterate over the objects in the tableEmployeeList object and then iterate over the missing property of each object, which is an array. It would then display the contents of the missing array for each object.

However, it's worth noting that this code is a bit confusing, as you are using the v-for directive to iterate over the objects in tableEmployeeList twice, but you only need to use it once. Also, you are using the tr element inside of another tr element, which is invalid HTML.

A better way to write this code would be something like this:

<tr v-for="employee in tableEmployeeList" :key="employee">
  <td >{{ employee.missing[0] }}</td>
</tr>

This code iterates over the objects in tableEmployeeList using a single v-for directive. It then displays the contents of the missing property for each object. However, this may require some changes to your data schema.

  • Related