Retrieving various properties of an object by matching IDs and displaying them without repeated reductions

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.

Answer №1

To simplify the process, you can map out the actions in a computed function and then prepare the table rows:

Vue SFC Playground

<script setup>
import { computed, reactive } from 'vue'

const players = reactive([{
  active: true,
  id: 0,
  name: "Alfred",
  action: 0
}, {
  active: true,
  id: 1,
  name: "Bruce",
  action: 1
}])

const actions = reactive([{
  id: 0,
  label: "Give advice",
  description: "Player advises others"
}, {
  id: 1,
  label: "Fight",
  description: "Player fights enemy"
}])

const playerTable = computed(() => players.map(player => {
  return {
    ...player,
    action: actions.find(action => action.id === player.action)
  }
}))
</script>

<template>
  <h1>TEST</h1>
  <table>
    <tr v-for="player in playerTable" :key="player.id">
      <td>{{ player.active }}</td>
      <td>{{ player.id }}</td>
      <td>{{ player.action.label }}</td>
      <td>{{ player.action.description }}</td>
    </tr>
  </table>
</template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

A guide on retrieving styled text from a database and displaying it in TinyMCE

I am encountering an issue where I need to retrieve formatted text from a database and display it in my TinyMCE editor. The content stored in the database looks like this: <p style="text-align: justify;"><strong>Zdrav&iacute;m</strong ...

Steps to create a dropdown select option using an AJAX call: When the data is fetched, it generates an array

How can I dynamically populate a dropdown with data from an array using jQuery and AJAX? <html> <script> $(document).ready(function() { $("#class_name").change(function(){ var class_id=$("#class_name").val(); ...

Understanding JSON Parsing in Jade

I am facing a challenge with handling a large array of objects that I am passing through express into a Jade template. The structure of the data looks similar to this: [{ big object }, { big object }, { big object }, ...] To pass it into the Jade templat ...

Why does the control skip the onreadystatechange function for the ajax object?

Just beginning my journey into web-development. Recently, I encountered an issue with a signup page I created that involves asynchronous calls to php. Upon debugging, I noticed that the onreadystatechange function is being completely skipped over. Any assi ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Instructions on utilizing the transpiled "main.js" file using gulp

As a novice in Angularjs 1.0, I encountered issues with my script and decided to use gulp to compile ec6 to ec5 by implementing the code provided below. The compilation process generated the file main.js. However, I am unsure about how to connect it when l ...

Accessing a document using protractor

It seems like every protractor example I come across online uses browser.get with a web URI. browser.get('http://localhost:8000'); I want to use Selenium to navigate to a local file:// path without needing a web server running. Just a simple HT ...

Having trouble getting your AngularJS code to work?

Recently, I decided to experiment with AngularJS and started working on a new project. Below is the HTML code I wrote: <div ng-app ng-controller="nameController"> <input type="text" value="Jack" ng-model="fname" /> <input type="tex ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method: localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}])); When I inspect it, this is how it ...

Uncovering the secrets: accessing hidden folder files in react-native-fs

I am encountering a problem when trying to access files from a hidden folder /WhatsApp/Media/.Statuses in react-native-fs. Despite granting the READ_EXTERNAL_STORAGE permission on Android, I only receive an empty array when attempting to access it using th ...

Show real-time server responses using jQuery while waiting for the AJAX request to complete

I have a challenge in creating a function that displays the server response while waiting for Ajax to complete. Here's the scenario: I have selected 10 checkboxes. When I click the submit button, Ajax is triggered. On the server side, there is a loo ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Please be aware that any fabricated comments will not be displayed in the posts object

-I have made an EDIT at the bottom of my original post -For my plunker, please visit this link Currently, I am learning AngularJS by following a tutorial located here. At this moment, I am stuck on the step called 'Faking comment data'. I have ...

Issue with ISO-8859-1 character encoding in table formatting

I have set my website to use ISO-8859-1 encoding and special characters are displaying correctly. However, I'm facing an issue with the datatables plugin which does not seem to recognize special characters in the table data. Do I need to configure an ...

Performing an RxJS loop to retrieve the httpGet response, followed by executing httpPut and httpPost requests based

I am currently working on a UI form that allows users to update or add translation text. To achieve this, I need to create an rxjs statement that will perform the following tasks: Send an httpGet request to the database to retrieve translations in mult ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

Sorting arrays in javascript

My JavaScript array is structured like this: var data_tab = [[1,id_1001],[4,id_1004],[3,id_1003],[2,id_1002],[5,id_1005]] I am looking to organize and sort them based on the first value in each pair: 1,id_1001 2,id_1002 3,id_1003 4,id_1004 5,id_1005 ...

Unlocking the potential of GraphQL: Harnessing the power of sibling resolvers to access output from another

Could use a little assistance. Let's say I'm trying to retrieve the following data: { parent { obj1 { value1 } obj2 { value2 } } } Now, I need the result of value2 in the value1 resolver for calculation ...