Refining Calculated Attributes

I am currently creating a list where you can add and remove elements while specifying the count of each added element.

I have included all elements in my data: Example:

[
  {
    "rowID": "21",
    "rowAnzahl": 1,
    "elementID": "127",
    "elementName": "Element 4"
  },
  {
    "rowID": "22",
    "rowAnzahl": 1,
    "elementID": "109",
    "elementName": "Element 3"
  },
  {
    "rowID": "",
    "rowAnzahl": "",
    "elementID": "106",
    "elementName": "Element 1"
  },
  {
    "rowID": "",
    "rowAnzahl": "",
    "elementID": "112",
    "elementName": "Element 2"
  }
]

Then I added two computed properties:

elements: function() {
      return this.testData.filter(function(e) {
        return e.rowID
      })
    },
    unusedElements: function() {
      return this.testData.filter(function(e) {
        return !e.rowID
      })
    },

Afterwards, I implemented the following methods:

methods: {
    addElement: function(index) {
      var item = this.testData[index];
      item.rowID = 'new' + this.rowCount++;
      item.rowAnzahl = 1;
    },
    removeElement: function(index) {
      var item = this.testData[index];
      item.rowID = '';
      item.rowAnzahl = '';
    }
  },

Now, I am facing an issue:

The index starts at 0 for my properties unusedElements and elements... However, since I require the index number for adding or removing the element, it is causing issues. Is there a way to filter the method by my elementID? Alternatively, can I set the elementID as the index number?

Thank you!

Answer №1

If you're looking to locate the position within an array, you can utilize the findIndex method:

var items = [...]; // Array
function findItemIndex(itemID) {
    return items.findIndex((element) => element.itemID == itemID);
}

Note: In case I misinterpreted your query, I'll keep this explanation for reference.

Answer №2

After some tinkering, I finally found a resolution by changing my approach. Instead of manipulating my data directly, I linked it to my computed properties.

    methods: {
    addElement: function(index) {
      var item = this.unusedElements[index];
      item.rowID = 'new' + this.rowCount++;
      item.rowAnzahl = 1;
    },
    removeElement: function(index) {
      var item = this.elements[index];
      item.rowID = '';
      item.rowAnzahl = '';
    }
  },

The straightforward solution with the index now functions flawlessly without any hiccups. Sometimes, all it takes is a little shift in perspective to tackle an issue successfully ;D

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

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

What could be causing the JSON String decode error to occur while utilizing extjs ajax?

Here is an example of my code: Ext.Ajax.request({ url:'test.jsp', params:{id:id,password:password}, success:function(response){ console.log(response); var results = Ext.util.J ...

The proper usage of middleware in vue-router

I've set up routes in Vue and added some middleware conditions before each route, but it's not functioning as expected. Below is the content of my router/index.js file: const token = computed(() => useAuthStore().token); // Main Router cons ...

I am having trouble with setInterval not functioning as expected. I am trying to make a function repeat every 500ms using setInterval, but it seems to be ineffective

var direction; function movement(){ switch(direction){ case 1: positionX = positionX + 10; break; case 2: positionX = positionX - 10; break; case 3: positionY = positionY - 10; bre ...

Children can easily access multiple items within a list by using the ul tag

I am struggling with changing the class of ul inside the ul.navigator. I want to change it only when I click on a particular li, but my current approach doesn't seem to be working. Can anyone provide some guidance or assistance? $('.navigator& ...

Tracking user sessions using cookies, not relying on JavaScript like Google does

Currently, I am working in an environment that utilizes PHP on the server side and Javascript on the client side. In order to monitor user sessions, I regularly send a JS PUT request to the server every 5 seconds. This allows me to gather data such as the ...

Tips for utilizing MUI Typography properties in version 5

I'm clear on what needs to be done: obtain the type definition for Typography.variant. However, I'm a bit uncertain on how to actually get these. interface TextProps { variant?: string component?: string onClick?: (event: React.MouseEvent&l ...

Get the PDF document via FTP by utilizing an XMLHttpRequest and a generic handler

Attempting to download a PDF file from an FTP server using a JQuery Ajax request. The reference used was found at . Below is the Jquery ajax call being made: $.ajax({ xhr: function () { var xhr = new window.XMLHtt ...

After installing Ember and running the Ember server, I noticed that the node_modules directory appears to be empty. This issue is occurring on my Windows 10 x64 PC

Welcome to the command console: C:\Users\Documents\emberjs>ember server node_modules seem to be empty, consider running `npm install` Ember-cli version: 2.14.2 Node version: 6.11.2 Operating System: Windows 32-bit x64 I'm a beg ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

Different methods to retrieve content within a div that is located on a separate, included page

It's a bit tricky to come up with a title for this topic, but essentially, I'm trying to figure out how to get content from an included page into a specific div using HTML and PHP. Let me break it down: In the header.php file, we have the follo ...

What is the best way to retrieve the local image path, transform it into a File object, and subsequently transfer it to firebase?

My current form includes a signup option where users can choose to upload a profile picture. In case they do not upload a profile picture, I aim to use a default one (think of the default Facebook profile picture). The image is imported as: import defaul ...

Verify if the user possesses legitimate Jira REST API credentials

I am currently using the npm module jira-client to send API requests to my Jira system. I need a way to verify whether the user has valid credentials before proceeding. Depending on the validation result, I plan to either: Inform the user that their use ...

Generating dynamic strings for identifiers in JSX

Can you help me figure out how to dynamically create IDs like this? <div id="track_1"></div> <div id="track_2"></div> I tried assigning the IDs from the parent component like this: export default function Compon ...

Guide on converting a JSON containing nested JSONs into an HTML table

Currently, I am working with a JSON data structure that contains nested dictionaries. My goal is to create an HTML table where each top-level key serves as a column in the table. The inner key-value pairs should be represented as a single text within cells ...

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...

In an empty JavaScript MVVM Organization View, the ViewModel is packed with lines of code

I find myself always placing all of my code within the ViewModel because nothing else seems to fit. What kinds of things should be included in the view? Does anyone have any examples? ...

Tips for transforming a UTF16 document into a UTF8 format using node.js

My dilemma involves an xml file that is encoded in UTF16, and I need to convert it to UTF8 for processing purposes. When I use the following command: iconv -f UTF-16 -t UTF-8 file.xml > converted_file.xml The conversion process goes smoothly with the ...