I'm curious if there's a better way of getting properties from a reduced object within a Vue or wrapper DOM element.
For example, 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'd like to loop through a list of options and return all results, with properties of the action within each player:
------------------------------------------------------------------
Active? ID Name Label Description
------------------------------------------------------------------
true 0 Alfred Give Advice Player advises others
true 1 Bruce Fight Player fights enemy
I know I can loop through the players like so:
<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>
With a method like this:
getActionProp(id, prop){
return this.actions.reduce((acc, cur) => {
return cur.id == id ? cur[prop] : acc
}, {})
}
But it seems like that has to reduce twice for each row in the table. Is there a better way to get these props or at least to make it so they only reduce once per row?
Something like:
<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>
with getAction()
being a method that reduces and returns the matching action object.
Thank you for your time and I appreciate your guidance.