Implementing an array of objects within a Vue method

I currently have an object called "Sorteio" which contains a vector of objects named "Resultado", consisting of 6 Resultados. The way I am creating instances of them is as follows:

saveSorteio() {
      var data = {
        loteria: this.sorteio.loteria,
        resultados: [
          {
            valor: this.sorteio.resultados[0].valor,
            animal: this.sorteio.resultados[0].animal
          },
          {
            valor: this.sorteio.resultados[1].valor,
            animal: this.sorteio.resultados[1].animal
          },
          /* ... */
        ]
      };
}

Is there a different method to instantiate all 6 at once, or do I need to continue calling index by index?

Answer №1

To extract specific properties from an array, you can utilize the #array.map() method in JavaScript.

saveSorteio() {
    var data = {
      loteria: this.sorteio.loteria,
      resultados = this.sorteio.resultados.map(({valor, animal}) => ({valor, animal}))

        /* ... */

    };
}

Here is an example to demonstrate how it works:

sorteio = {
    resultados: [
        {valor: "v1", animal: 'a1', somethingelse:"else"},
        {valor: "v2", animal: 'a2', somethingelse:"else"},
        {valor: "v3", animal: 'a3', somethingelse:"else"}
    ]
}
let newArray = sorteio.resultados.map(({valor, animal}) => ({valor, animal}))
console.log(newArray)

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

Here's a unique version: "Strategies for effectively closing a modal when moving to a

I'm currently working with react-router-dom and material UI modal, and I am looking for a way to automatically hide the modal whenever the user navigates to another page. Here is my App component: const App = () => ( <BrowserRouter> &l ...

Failed to load CSS file in nodeJS application

I followed a tutorial to create a backend app using nodeJS and Express. My MongoDB connection with Mongoose is working fine. However, I am facing issues when trying to add a simple front-end using html/ejs/css. The endpoints are loading on localhost but on ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

The attached event in my Nuxt.js project fails to fire during testing with Jest

I'm currently in the process of developing a web application using nuxt js + jest Here is an excerpt from my nuxt js component: export default { mounted () { document.addEventListener('click', this.eventClick) }, destroyed () { ...

React TextField is not accommodating the new line character ' ' causing recognition issues

Explanation I have encountered an issue while using Material UI TextField and mapping through an array of objects fetched from a MongoDB database. Here is the code snippet in question: {state.map((item) => ( <TextField name=" ...

Q-Node - managing an array of Q elements

Having an array of elements like this: var arr = [1, 2, 3, 4, 5, 6, 7, 8], my objective is to apply a specific action to each element sequentially. I don't want these actions to be performed in parallel. For instance: arr.forEach(function(d){ //s ...

Transforming an individual array into a multi-dimensional array

Just to be upfront, I had to figure this out for a project. I needed to convert a single array into a multidimensional array within a method. To solve the problem, I came up with the following code by first returning it to another one-dimensional array and ...

Changing the background color of a page to match the background color of a button in React, which can be updated at any time

I have a special button called ArbitraryBtn that, when clicked, changes the page's background color to random colors: import React from 'react'; export const changeToArbitraryColor = () => (document.body.style.backgroundColor = ...

When attempting to read data from a list and not an array, a numpy error occurs as it is unable to perform

I am attempting a basic regression analysis by extracting columns from a CSV file and using numpy and stats for the regression. The code successfully prints x or y, but encounters an error on the final line of code. Line 62, in _mean ret = um.add.red ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

"Challenges Encountered When Implementing CSS Card Flip

Can anyone help me with a strange problem I'm experiencing with my css card flip code? The card seems to only flip when I move my mouse away from it. Any insights on what might be causing this behavior? Thank you in advance for any assistance. ...

Utilizing namespacing in a JavaScript library can enhance organization and flexibility, providing

Creating a JavaScript library with multiple modules is my next project. Imagine the library is named Library, with modules One and Two. My goal is to allow end users to call the library in two ways: Library.One.somefunction(params) or somefunction(param ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...

What is the best way to show and hide text by toggling a link instead of a button?

I need help with toggling between two different texts when a link is clicked. I know how to achieve this with a button in JQuery, but I'm not sure how to do it with a link. <h1>Queries and Responses</h1> <p>Query: What is the larges ...

Transmit messages from server (via Expressjs routing) to the client

I am looking for guidance on how to effectively send messages from the server to the client and incorporate this functionality into routes/index.js within my mean stack project. Can anyone provide insights on using socket.io in this context?: router.post( ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Unchecking and checking the radio button is necessary in order for it to function properly

Today, I'm puzzled by the odd behavior of my radio buttons in a pixel drawer project. In order for the radio button to function properly, I have to uncheck it and then recheck it. The pixel drawer allows me to change colors and sizes using these radio ...

The installation of npm was unsuccessful due to an error: npm encountered an invalid JSON response

Warning: Peer dependency overridden by npm. Found: [email protected] in node_modules/@ivan/data-insights/node_modules/bootstrap. Bootstrap@^3.3.7 from @ivan/[email protected] version 1.7.26. Could not resolve dependency because peer bootstrap@^4.3.1 nee ...