Vue.js - Exploring methods to append an array to the existing data

I am looking to structure my data in the following way:

Category 1

  • Company 1
  • Company 2
  • Company 3

Category 2

  • Company 1
  • Company 2
  • Company 3

Below is my code snippet:

getlist() {
      var list = this.lists;
      var category
      
      this.$http.get("/getlist")
      .then((res) => {
          var obj = res.data;
          for(var [key] in obj) {
              var company =[];
            for(var i in obj[key].company) {
                company.push( obj[key].company[i].name)
            }
              console.log(company);
              list.push({
                  "category_name" : obj[key].name,
                  "companies": [
                      {name: company}
                      ]
              })
              list.category_name = '',
              list.companies = '',
              company= ''
          }
      })
  },

The structure of my list should appear as follows:

         {
                category_name: 'Category1',
                companies: [
                    {name: 'Company1'},
                ]
            },

Here is an example of how the data should look:

[
    {
        "name": "Category2",
        "company": [
            {
                "name": "Company1"
            }
            {
                "name": "Company2"
            }
        ]
    }
    {
        "name": "Category2",
        "company": [
            {
                "name": "Company1"
            }
            {
                "name": "Company2"
            }
        ]
    }

]
I'm struggling with implementing a for loop in this scenario.

Is it possible to use a double for loop within list.push()?

This problem is proving to be quite challenging for me.

Answer №1

It seems like your intention is to update the keys for data objects you receive from the server.

This piece of code should help you achieve that:

fetchData() {
  this.$http.get('/getData')
    .then(response => {
      let updatedList = [];
      for (let item of response.data) {
        let updatedItem = {
          category_name: item.name,
          companies: item.company
        }
        updatedList.push(updatedItem);
      }
      this.dataList = updatedList;
    })
    .catch(error => {
      console.error('An error occurred while fetching data:', error)
    });
}

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

How can I create a React component that is accessible and controllable from external sources?

Attempting to create a Dialog component using React and Material-UI. Currently, the component behaves like a traditional Material-UI dialog with a button inside the class that opens the dialog. However, I aim to achieve the same behavior as the default Ma ...

Steps for raising a unique error in an asynchronous callout

As I work on making async API callouts, there might be a need to throw custom errors based on the outcome. Also, part of this process involves deleting objects from S3. try { await s3.deleteObject(bucketParams); //Since S3 API does not provide ...

Using Knex.js to perform a case-insensitive search on an object with the whereIL

Still searching for a solution to this problem. I am attempting to pass an object with filters as keys and values. ex. const filters = { 'id': 12, 'first_name': john } function findBy(filter) { return db('quotes') ...

Encountering difficulty importing a module from a different module within Nuxt

Within my Nuxt project directory, there exists a specific folder named modules which houses my customized modules. For this illustration, it includes the modules foo and bar. The inclusion of foo in the nuxt.config.js file appears as follows: // nuxt.confi ...

JavaScript: table is not defined

When creating a table using Django models and JavaScript, I encountered an issue where the cells values of the table could not be accessed from another JavaScript function. The error message indicated that the table was "undefined". Below is the HTML code ...

Deviations in Scriptaculous Callbacks during Movement Effects

I am looking to create a dynamic menu item that moves out 5px on mouseover and returns to its original position using Scriptaculous. I have implemented the afterFinish callback to ensure that the bump-out effect is completed before the item moves back in. ...

Encountering an "undefined is not a function" error across all libraries

While working on ASP.Net MVC4, I have encountered an issue where I consistently receive the error message "undefined is not a function" when using jQuery functions with different libraries. Despite ensuring that every ID is correct and everything has bee ...

Tips for emphasizing matches within a string using JSX

I've implemented a custom autocomplete feature that suggests options based on user input. I want to highlight the characters in the suggestions list that match the input value. For example, if the suggestion list includes "alligator", "lima", and "li ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Error: The data from the intermediate value cannot be parsed using the parseFromString() method and replaced with another value,

I'm working on a project where I need to display parsed HTML content within an element. However, before displaying it, I need to make some changes to the HTML using the `replace` method. But unfortunately, I encountered a TypeError: (intermediate valu ...

Attempting to enhance the modularity and readability of my code

Looking for assistance to enhance the modularity and readability of this lengthy code. Any tips on how to simplify it and improve clarity would be greatly appreciated! I'm currently working on a street fighter game, and here's what I have so far ...

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

Display a single button on hover in Angular 2+ framework

I'm looking to have the 'Edit' button only appear when I hover over a selected row. Here's the code: https://stackblitz.com/edit/inline-edit-change-edit2-j8b2jb?file=app%2Fapp.component.html I want the 'Edit' button to show u ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

Firebase predeploy error code 254 detected

Upon attempting to deploy my website using the command firebase deploy, I encountered the following error: === Deploying to 'project'... i deploying database, functions, hosting Running command: npm --prefix "%RESOURCE_DIR%" run lint npm ERR! ...

Error Encountered when Trying to Utilize Vue Component Getter in TypeScript Mixin (Error Code: TS233

Here is the code snippet that I am currently working with: import {Component, Vue} from 'vue-property-decorator'; @Component({}) export default class MyMixin extends Vue { scrollToTop(): void { let scrollingWrapper: any = (this.$refs[th ...

ReactJS is encountering a situation where two children are using the same key and causing

When I try to view the profile information of another user, I encounter a duplicate key error that says: "Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique k ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Rotational orientation of a progress circle image in SVG

I am currently working on developing a circular progress bar, similar to the one shown in the image below. The progress of this bar is determined by percentages and it moves around the circle accordingly. I have managed to get the progression moving, b ...