I have a function inside a loop that takes the currently looped match and returns a participant with certain name. How to avoid duplication?


Couldn't fit my entire question in the title so I'll add it here as well.

I currently have a loop that creates a div element for each match and in that div I want to display the information of ONE of the 10 match participants. For this, I use a function that returns the object of a participant with a certain name. However, as you can see below, every time I want to access a property of that participant, I have to use the function again and again for each property.

I don't think that is the right course of action right? I'm using Vue.js as a front-end framework.

Currently I have the following code:

Loop:

<div v-for='match in summonerMatches.matches'>
    {{ findParticipant(match).championId }}
    {{ findParticipant(match).spell1Id }}
    {{ findParticipant(match).spell12d }}
</div>

Function:

findParticipant(match){
    let participantId = match.details.participantIdentities.find(x => x.player.summonerName === this.summonerInfo.name).participantId;
    let participant = match.details.participants.find(x => x.participantId === participantId)

    return participant
}

Obviously if this function wasn't in a loop, I'd just save the participant object and then access it, however, since it's inside a loop I've no idea how this would happen.

Use a computed property that stores all participants in an array. For example ..

data() {
...
},
computed: {
    participants() {
        return this.summonerMatches.matches.map(match => this.findParticipant(match))
    }
}

Then in your template you can loop over the participants instead ..

<div v-for="participant in participants">
    {{ participant.championId }}
    {{ participant.spell1Id }}
    {{ participant.spell12d }}
</div>

You should do a loop of a object list already loaded with the "participant" information.

I'm typing from my mobile, let's see if It is possible to explain..

Best approach would be do a query in the back end filtering and loading the object participants whitout duplication. The view should only print things, don't do any processing...

If you only don't want duplicate the div you could create the divs using the IDs of "participant" in the property ID, in this way you would avoid to create new ones just checking if it already exists in the HTML page...