Using a double for loop in VUE3 without altering the property

I am working with a 'data' props object that looks like this:

data = [
    {
      "label":"gender",
      "options":[
        {"text":"m","value":0},
        {"text":"f","value":1},
        {"text":"x", "value":null}
      ]
    },
    {
      "label":"age",
      "options":[
        {"text":"<30", "value":0},
        {"text":"<50","value":1},
        {"text":">50","value":3}
      ]
    }
  ]

In a computed property, I want to create a new array that is identical to the data prop, except that I need to multiply the value in the options array by 2. Previously, in plain JavaScript, I achieved this using the following code:

data.forEach(item => {
    item.options.forEach(option => {
      if (option.value !== null && option.value !== 0) {
        option.value *= 2;
      }
    })
  });

Now, I am attempting to do this within a computed property using .map(), so that it does not modify my original data props. However, I am struggling to implement it correctly. Here is my attempt:

computed: {
  doubledValues() {
    var array = this.data.map((item) => {
      //...
      item.options.map((option) => {
        //... option.value * 2;
      });
    });
    return array;
  }
}

Answer №1

To implement this functionality, simply utilize the map() method as demonstrated below:

computed: {
doubledValues() {
  return this.data.map(item => ({...item, options: item.options.map(obj => {
    return (obj.value != null) ? { ...obj, value: obj.value * 2 } : { ...obj }
  })})
  );
}
}

Answer №2

To duplicate objects/arrays, you can use the following code snippet:

computed: {
  clonedValues() {
    return this.data.map((obj) => {
      const newObj = {...obj};
      newObj.options = obj.options.map((opt) => {
        const duplicatedOption = {...opt};
        if (duplicatedOption.value !== null && duplicatedOption.value !== 0) {
          duplicatedOption.value *= 2;
        }
        return duplicatedOption;
      });
      return newObj;
    });
  }
}

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 save nested lists in a MYSQL database?

I am trying to figure out the best way to store this list of lists in MySQL, but I'm not sure how to go about it. list[x][y] contains items structured as {li:[{x:x,y:y}] , pos:{x:y}} list[x][y].li[z].x list[x][y].li[z].y list[x][y].pos.x list[x][y]. ...

Exploring Vue's "is" Attribute with Web Components

I've encountered an issue while trying to utilize a web component that extends an existing element using the "is" attribute tag within Vue. The problem is that Vue takes this attribute and transforms it into a custom element. While I still want Vue t ...

The Vue backdrop is hiding the Bootstrap modal

After attempting to integrate a modal into a component, I encountered an issue where the backdrop appears in front and the modal is hidden behind it as shown below. I have reviewed all the position CSS properties within the parent components but could not ...

The error message from Object.create() indicates that the argument provided is not recognized as

Description Within my project, I am handling a JSON file, parsing it into an object, and attempting to transform it into an instance of the ProjectFile class using Object.create(). Code let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf- ...

The integration between React.js, Node.js, and Express.js is facing issues with the socket.io functionality

I am currently working on integrating socket.io with React.js, running the socket.io on a backend server using Express.js. One issue I am facing is that when an order is placed on the homepage, it should be displayed in real-time on the Orders page in Rea ...

Navigating through the keys of a parameter that can assume one of three distinct interfaces in TypeScript: a guide

Here is a function example: function myFunc(input: A | B | C) { let key: keyof A | keyof B | keyof C; for(key in input) { let temp = input[key]; console.log(temp); } } The definitions for A, B, and C are as follows: interfa ...

Creating dynamic TextBox fields in JSP based on the selected option from a dropdown menu fetched from the database

Hello, I need some assistance in creating dependent Textboxes based on Dropdown values fetched from a database using Jsp. The code provided below is working fine for one Textbox, but I am unsure how to extend it for multiple dependent Textboxes. Any help w ...

Struggling to understand the javascript snippet "requiring the passport file and passing in passport as a parameter."

I am still learning the ropes of javascript and currently working on a basic login restful api using the passport middleware. I understand that when I use require('xxxxx'); I am importing a module for use. While researching online, I came across ...

"if the condition is not met, the outcome will not be shown in the while

I have a looping structure that includes conditions for if, else if, and else. However, I have noticed that the else condition at the end of the loop is not being executed as expected. I am currently investigating why this might be happening. Here is the ...

Is it possible to adjust the size of the new window based on changing requirements?

I have a setup where my JSP file is linked with a JS file. I want a new window to display a photo every time the link is clicked. Currently, everything is working fine and a new window pops up, but it has fixed width and height specifications. else if (na ...

What is the reason for the global error handling middleware being executed post sending the response in express js?

Why is the global error handler being reached and the value of "err" is 404 when I am sending the response from the /test route? The request-response cycle should end at that point, so why is it not throwing an error in the response but logging 404 to the ...

Vuex - Avoid changing the vuex store state directly without using mutation handlers or getters

/pages/index.vue computed: { getFirstValue() { return this.$store.state.escapeOnline.slice(0, 1); } } /store/index.js export const state = () => ({ escapeOnline: [{id: 1, name: 'titi'}, {id: 2, 'toto'}], }) Whenever I attem ...

What is the best way to resize images to fit in a 200 pixel square box using CSS?

I have a collection of images that all fit within a 400px × 400px box, with one dimension being 400px and the other smaller. I want to resize these images using CSS or jQuery/JavaScript if necessary, to fit into a 200px by 200px box. The goal is to have t ...

I am just starting to explore firebase and I'm having trouble organizing my data. I've attempted to use the query function and orderBy

After experimenting with query and orderBy() methods, I'm still struggling to properly integrate it into my code. Here's what I have so far: Methods: async saveMessage(){ try { const docRef = await addDoc(collection(db, "chat"), ...

Issue with Javascript redirect not working following form submission in combination with Asp Classic

After countless hours of research and experimentation, I find myself at a standstill. My web page is coded extensively, so I'll do my best to provide a concise summary. The core elements of my ASP CLASSIC page for creating tickets via a form are as f ...

The component fails to update after a change in state

I'm currently working on a project that involves fetching videos from YouTube and displaying them on the browser. I have successfully retrieved the videos and updated the state property (confirmed using console log). However, I am facing an issue whe ...

What is the best way to display hover-over text pop ups on menu list items in jsTreeR?

As a dedicated user of the jsTreeR package within Shiny, I have been exploring the functionality it offers. By executing the code below, users are presented with a draggable menu at the top, allowing them to drag items down to the designated list labeled " ...

choose all the choices with jQuery

Is there a way to implement a select all feature for an option list using jQuery? Basically, I want to be able to select all the option elements within the same class (class 11) when the parent option (Option Pa1) is selected. How can this be achieved? ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

Differences between React Router's createBrowserRouter and Browser RouterWhen it

As I embark on a fresh React endeavor, my goal is to incorporate the most up-to-date version of React Router. According to the documentation, createBrowserRouter is the preferred choice for web projects. While they mention that it allows for certain data A ...