user2410266
user2410266

Reputation: 551

Display data object based on condition in for loop using Vue.js

I have an array of objects,I would like to display data based on some condition.If the user id matches with data id display name,age for that id.Also is it possible create single divs and display multiple div by looping instead of defining it 3 times for 3 different id.

              <div class="content" v-for="person in persons>
              <div v-for="user in users"
              :key="user.id">
                  <div v-if="user.seqId == person.id" >
                   {{person.name}}          
                  </div>
                <div v-if="user.seqId == person.id">
                   {{person.name}} 
                  </div>
                </div>
                <div v-if="user.seqId == person.id">
                   {{person.name}}  
                  </div>
                </div>
                </div>

            const persons= [
                {
                   name: 'Adam',
                   age:20,
                   id: 1,
                },
                   {
                   name: 'Paul',
                    age:20,
                    id: 2,
                },
                {
                  name: 'James',
                  age:20,
                  id: 3,
                 },
                 ]
              data() {
                return {
                  persons,
                  };
                  }

Upvotes: 0

Views: 865

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362620

Create a computed property to merge the matches into a single array..

computed: {
    matchingUsers() {
        // find persons that exist in users by
        // matching p.id == u.seqId
        return persons.filter(p=>{
            return users.find(u=>u.seqId===p.id)
        })
    }
}

Then iterate the single array...

<div class="content" v-for="(person,i) in matchingUsers" :key="i">
    {{person.name}} - {{person.age}}
</div>

Codeply demo

Upvotes: 2

Related Questions