Search code examples
jsonvue.jsv-for

V-If inside V-for, inside V-for


I am a newbie with Vue and I am trying to run an IF statement inside two v-fors. Basically I am trying to compare a value from one array of objects to a value of another array of objects and if true, render value from array of objects No 2.

Here is the code.

      <div v-bind:class="[isActive ? 'projectsWorkingOnActive' : 'projectsWorkingOnInactive']" v-for="rec in listOfEmployees" v-bind:key="rec.id" >
        <div v-for="proj in dummyProjectsData" v-bind:key="proj.id">
          <div v-if="rec.name.display_value == proj.task_owner">
            <h3>Projects Working On</h3>
            <ul>
              <li><a href="">{{proj.projects_working_on.project_name}}</a></li>
              <li><submitbutton button_label="Hide Projects" @click="toggleClass()"></submitbutton></li>
            </ul>
          </div>
        </div>
      </div>

And here are my 2 arrays of objects.

    const dummyProjectsData = [
  {
    ID: "44000005501077",
    task_owner: "Denis Denchev",
    projects_working_on: [
      {
      "project_name": "Project-1",
      "project_id": "195000002362044"
      },
      {
      "project_name": "Project-2",
      "project_id": "195000002362045"
      },
      {
      "project_name": "Project-3",
      "project_id": "195000002362046"
      },
    ]
  },
  {
    ID: "44000005501078",
    task_owner: "Jake Jones",
    projects_working_on: [
      {
      "project_name": "Project-2",
      "project_id": "195000002362044"
      },
      {
      "project_name": "Project-5",
      "project_id": "195000002362045"
      },
      {
      "project_name": "Project-3",
      "project_id": "195000002362046"
      },
    ]
  },
]

And the second array...

 const listOfEmployees = [
  {
    "ID": "44000005527013",
    "name": {
     "display_value": "Denis Denchev",
     "first_name": "Denis",
     "last_name": "Denchev",
     "prefix": "",
     "suffix": "",
    }
  }
]

What am I doing wrong? It must be something silly that I am missing? Or can I not do if statement taking value from two v-for's ?


Solution

  • The problem is that proj.projects_working_on is an array of multiple projects, but you are trying to access a property on it like an object. Change to something like:

    <div v-bind:class="[isActive ? 'projectsWorkingOnActive' : 'projectsWorkingOnInactive']" v-for="rec in listOfEmployees" v-bind:key="rec.id" >
      <div v-for="proj in dummyProjectsData" v-bind:key="proj.id">
        <div v-if="rec.name.display_value == proj.task_owner">
          <h3>Projects Working On</h3>
          <ul>
            <li v-for="p in proj.projects_working_on" v-bind:key="p.project_id">
               <a href="">{{ p.project_name }}</a>
            </li>
            <li><submitbutton button_label="Hide Projects" @click="toggleClass()"></submitbutton></li>
          </ul>
        </div>
      </div>
    </div>