How can you append an object with a defined key to an array in Vue?

Currently developing a vue-application that includes a component for managing driving licenses.

Here is an overview of my data setup:

data() {
   return {
     custom_licenses: [],
     basic_licenses: []
   }
}

Within my methods, I have the following logic:

regular_licenses() {
  this.$store.dispatch("license/read").then(response => {
    response.licenses.map((license, key) => {
      // PUSH LICENSES WITH TYPE 'BASIC' TO this.basic_licenses
      // PUSH LICENSES WITH TYPE 'CUSTOM' TO this.custom_licenses
    });
  });
},

In the creation stage (created()), the method this.regular_licenses() is called.

The result obtained from the dispatch call looks like this:

licenses: 
 [
   {
     id: 1, 
     type: 'basic', 
     name: 'AMa'
   },
   {
     id: 2, 
     type: 'basic', 
     name: 'A2'
   }, 
   {
     id: 3, 
     type: 'basic', 
     name: 'C'
   },
   {
     id: 4, 
     type: 'custom', 
     name: 'C1'
   }, 
   {
     id: 5, 
     type: 'custom', 
     name: 'D'
   },

   and so on...
 ]

Now, the goal is to iterate through the array and appropriately categorize them into custom_licenses and basic_licenses based on the type attribute - any suggestions on how to tackle this task?

Answer №1

Give this a shot

fetch_licenses() {
  this.$store.dispatch("license/read").then(response => {
    response.licenses.map((license, key) => {
      switch (license.type)
        case 'basic':
          this.basic_licenses.push({ ...license });
          break;
        case 'custom':
          this.custom_licenses.push({ ...license });
          break;
    });
  });
},

Answer №2

Make sure to Update your Code Block:

 response.licenses.map((license, index) => {
   // Move all licenses with the type 'BASIC' into basic_licenses array
    if(license['type'] == 'basic') {
        // Create a deep clone of the license object
        let tmpLicense = JSON.parse(JSON.stringify(license));
        basic_licenses.push(tmpLicense);
    } else if (license['type'] == 'custom') {
    // Move all licenses with the type 'CUSTOM' into custom_licenses array        
        // Create a deep clone of the license object
        let tmpLicense = JSON.parse(JSON.stringify(license));
        custom_licenses.push(tmpLicense);
    }  
  });

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 index type 'X' is not allowed for use in this scenario

I encountered an issue in my TypeScript code: error message: 'Type 'TransitionStyles' cannot be used as an index type.' I'm wondering if there's a way to modify my interface so that it can be used as an index type as well: ...

Is there a translation issue affecting Chrome version 44?

Recently, Chrome 44 (44.0.2403.89 m) was released and I've encountered some issues with the translate3d feature (on both Mac and Windows versions). This problem is impacting plugins such as fullPage.js and consequently affecting numerous pages at th ...

Converting a multi-dimensional array to a single array in JavaScript: the ultimate guide!

I have encountered a scenario in my application where there is an array with multiple arrays nested inside: https://i.sstatic.net/3uHP9.png I am looking to transform this structure: [ { "tag": [ { "key": "asda ...

What are the steps to customize the format of Vue3 Datepicker extensions?

Is there anyone who can lend a hand? I am currently using the Vue3 Datepicker and I have received a value that looks like this Thu Jun 23 2022 17:14:00 GMT+0700 (Western Indonesia Time) Does anyone know how to transform it into the following format? Thu, ...

Using setTimeout to click and hold on an element in Javascript

I am in need of adding a feature to my web app where a specific action is triggered when the user clicks and holds on an element, similar to the long press on Android. Here is the HTML code for my div: <div id="myDiv" onmousedown="press()" onmouse ...

How to Decode jQuery Array in PHP

I'm currently working on a PHP script where I need to retrieve the value of an array using the POST method. var data = []; table.rows({ selected: true }).every(function(index){ // Get and store row ID data.push(this.data()[0]); //creating a ...

Retrieve a single value from a JavaScript array

There must be something simple I am missing here, as all the search results I found relate to looping over arrays, which is not what I want. My ajax call returns a response in the form of a straightforward array. When I use console.log(response); in the s ...

I'm looking for the location of the console.log output while running nodejs/npm start. Where

Just started working with react/node and using npm start to launch a server. The server is up and running, displaying my react code as expected. However, I'm facing an issue with debugging - my console.logs are not showing up in the browser console. I ...

"An error occurred when processing the JSON data, despite the JSON

Incorporating Ajax syntax for datatables and angularjs has been my current endeavor. Encountering an invalid JSON response with the following: self.dtOptions = DTOptionsBuilder.fromSource([{ "id": 860, "firstName": "Superman", "lastName": "Yoda" }]) How ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

"Utilizing Vue-auth to Restrict Access to a Route Based on User Role - A Step-by-Step Guide

My initial Laravel application development involves using Vue-js in a single-page application (SPA). I am attempting to restrict access to a route (view-router) based on user roles. To manage roles, I am utilizing the spatie/laravel-permission package. ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

Issue with form action redirection on Node JS Express server not functioning correctly

My EJS application involves using jQuery in the JavaScript code to fetch JSON data from the Google Custom Search API. The app then uses the GET method to navigate to /search, passing the query as the attribute for q. Here's an example of the form&apos ...

What is the best way to submit a Redux Form only if there have been changes made to any of the fields

I'm currently using Redux Form version 7.1.2, and I have a form that submits data when the user clicks the submit button. In the function assigned to handle the submission, I perform an action. However, I only want this action to be executed if there ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Issue with marker functionality on Google Maps JavaScript API when conditions are not functioning correctly

I am currently working on plotting different markers on Google Maps by extracting data from a CSV file. I have incorporated the parsecsv-0.4.3-beta library to read the CSV file, and everything is functioning smoothly except for when I compare two fields to ...

Rails : CSS/JavaScript functioning perfectly on local server, facing issues on Heroku deployment

My Rails website features various CSS animation effects and JavaScript elements. While these transitions function smoothly on my local environment, they do not work properly on Heroku. Examining the Heroku logs: 2013-09-17T17:13:36.081145+00:00 app[web.1 ...

What sets onEnter apart from onStart in ui-router?

I am transitioning to the latest version of ui-router (1.0.0-alpha.5) and I am exploring how to utilize the onEnter hook versus the onStart hook: $transitions.onStart() as well as $transitions.onEnter() In previous versions, we only had the event $sta ...

Breaking down a URL based on one of two distinct components

Currently, I have a piece of code that splits the URL and removes everything after &7. Is there a way to modify it so that it also checks for |relevance simultaneously and splits based on whichever one is found? $(document).ready(($) => { const pa ...

"Utilize Selenium to navigate and select a menu option with a

In my dropdown menu, I am trying to use Selenium to move the mouse to the Documentation menu item and click on the App Configuration option within it. The mouse hover function is working properly, but I am unable to click on the App Configuration element. ...