Is there a way to retrieve arrays nested within an object in Vue or JavaScript?

In my Vue instance, I have a data object named items

<script>
export default {
  data() {
    return {
      selected: "",
      items: {
        item1: [{ selected: "", inputType: "", inputTarget: "" }],
        item2: [{ selected: "", inputType: "", inputTarget: "" }]
      },
      textarea: ""
    };
  },
  methods: {
    selectboxAction(index) {
      this.items.item1.forEach(val => {
        if (val.selected.toLowerCase() === "file") {
          this.$refs.inputData[index].type = "file";
        } else {
          this.$refs.inputData[index].type = "text";
        }
      });
    }
  }
};
</script>

How can I retrieve an array of items? I want to apply conditions to each item, even though there could be more than just two items, potentially up to 100 in the future.

In the selectboxAction method, I can only access the item1 array. How can I access all arrays within the items object, not just item1?

Answer №1

One approach would be to organize your data utilizing a computed getter, as well as implementing Object.keys as others have recommended.

get itemsArray() {
  return Object.keys(this.items).map((key) =>
    return this.items[key];
  });
}

Answer №2

Consider restructuring your data model by using an array for 'items' instead of individual properties like 'item1', 'item2', and so on. It's recommended to include an 'id' property for each item in the 'items' array:

  data() {
    return {
      selected: "",
      items: [
        { id: 1, selected: "", inputType: "", inputTarget: "" },
        { id: 2, selected: "", inputType: "", inputTarget: "" }
      ],
      textarea: ""
    };
  },

Answer №3

Here is a way you can achieve this:

 methods: {
    handleSelection(index) {
      Object.keys(this.options).forEach(value => {
        this.options[value].forEach(option => {
          if (option.selected.toLowerCase() === "file") {
            this.$refs.inputFields[index].type = "file";
          } else {
            this.$refs.inputFields[index].type = "text";
          }
        });
      });
    }
  }

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

The type 'IProduct' cannot be assigned to type '[]'

Looking for help with dispatching events between parent and child components. Interfaces: export interface IProduct { id: string; name: string; price: string; image: string; inStock: number; fastDelivery: bo ...

How should I properly initialize my numeric variable in Vue.js 3?

Encountering an issue with Vue 3 where the error message reads: Type 'null' is not assignable to type 'number'. The problematic code snippet looks like this: interface ComponentState { heroSelected: number; } export default define ...

What causes the Woocommerce checkout button to be blocked on the checkout page?

I am perplexed by WooCommerce's decision to block this section of the screen with an overlay. Under what circumstances would it do so? checkout page screenshot ...

Steps for triggering the material-ui menu to appear on hover of a button

I attempted to implement the following code without success. I was able to achieve it using plain CSS, but I need to utilize the makeStyles function provided by material-ui. My goal is to display a drop-down list of items when a user hovers over the butto ...

Binding values in Vue.js with a prefix and suffixCreating bindings in Vue

I attempted to bind a value to an input by using a variable declared in the data object, but I also need to include a prefix and a suffix. <input id="topnavback", v-bind:value="rgb({{themestopnavback}})", class="jscolor"/> The value "themestopnavba ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

The process of using Jest to test whether a React component correctly renders a list

I've been diving into the world of unit testing and recently developed a small React application that showcases a list of Pokemon. My goal is to create a unit test that verifies if the list renders correctly. However, when I generate a snapshot, it on ...

Having trouble establishing a connection between MongoDB Atlas, NodeJS, and Mongodb

Encountering an issue while attempting to establish a connection with MongoDB. The error seems to be related to the 'connect' keyword itself. I am unsure of what the exact problem is. The error message displayed is as follows: mongodb.connect( ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

What is the process for transferring an environment.json file to the output directory and then utilizing it with Webpack 4?

Our application is expanding with multiple environments and vendors on the horizon. While the traditional approach of running webpack --env.NODE_ENV=myenvironment works for now, it will soon become inefficient. The main objective here is to streamline the ...

The object FormData cannot be instantiated as a constructor

I'm currently facing an issue while trying to create an AJAX request to upload an image. The problem arises when I attempt to initialize the FormData object. The error message in my console states: "dataForm is not a constructor". Any ideas on how I ...

What is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...

The problem with the CSS Grid effect

Looking for assistance in creating a grid layout similar to the one on this website: Upon inspecting the page source, I found the following code snippet: http://jsfiddle.net/o45LLsxd/ <div ng-view="" class="ng-scope"><div class="biogrid ng-scope ...

Converting a blob to base64 and then back to a blob in Node.js may result in varying sizes between the two

I am currently implementing this code in a Node.js application. I have a blob that I am converting to a base64 string and then back to a blob using the following method: // Converting Blob to base64 string via Buffer const buffer = Buffer.from(await myBlob ...

Seeking guidance on Ajax .... in need of clarification

Could someone provide an explanation for this code snippet: const greeting = 'hi'; $.ajax({ type: "POST", url: "check.php", data: "greeting="+greeting, success: function(response){ alert( "Response received from server: " + resp ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...

Divide HTML elements every two words

Can you use CSS to break up HTML content after every 2 words, ensuring it works for any word combination? Example: // Original HTML content The cat is sleeping // Desired result: The cat is sleeping ...

Tips for saving HTML data locally

Is there a way to persist my HTML element tag data even after the user closes the browser? For example: <div class="classOne" data-random="50"> If I use jQuery to change the data attribute like this: $(".classOne").attr("data-random","40") How ca ...

Can all the files in a folder be imported?

I have a plethora of files including .css, .jpg, etc. stored in a directory named "assets", and I am looking for a way to import all of them recursively. Is there a python-like solution for this task? from './assets' import *; Instead of manual ...