I'm interested in finding a more efficient way to retrieve properties from a reduced object within a Vue component or wrapper DOM element.
Let's say I have these two data objects in my component:
player: [{
active: true,
id: 0,
name: "Alfred",
action: 0
}, {
active: true,
id: 1,
name: "Bruce",
action: 1
}],
actions: [{
id: 0,
label: "Give advice",
description: "Player advises others"
}, {
id: 1,
label: "Fight",
description: "Player fights enemy"
}]
...and I want to iterate through a list of options and display all results, including properties of the action associated with each player:
------------------------------------------------------------------
Active? ID Name Label Description
------------------------------------------------------------------
true 0 Alfred Give Advice Player advises others
true 1 Bruce Fight Player fights enemy
I am aware that I can loop through the players like this:
<table>
<tr v-for="(player, index) in players" :key="index">
<td>{{ player.active }}</td>
<td>{{ player.id }}</td>
<td>{{ this.getActionProp(player.action, 'label') }}</td>
<td>{{ this.getActionProp(player.action, 'description') }}</td>
</tr>
</table>
Using a method like this:
getActionProp(id, prop){
return this.actions.reduce((acc, cur) => {
return cur.id == id ? cur[prop] : acc
}, {})
}
But it feels like it has to reduce twice for each row in the table. Is there a more optimal way to retrieve these properties, or at least reduce them only once per row?
Maybe something along the lines of:
<table>
<tr v-for="(player, index) in players" :key="index">
<td>{{ player.active }}</td>
<td>{{ player.id }}</td>
<template :action="getAction(player.action)">
<td>{{ action.label }}</td>
<td>{{ action.description }}</td>
</template>
</tr>
</table>
using getAction()
as a method to perform just one reduction and return the matching action object.
Thank you for taking the time to read this, I value your insights.