Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach:

error_reporting(E_ALL);
ini_set('display_errors', '1');

require '../vendor/autoload.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");


$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->hotel->airlines;


$cursor = $collection->find();

echo json_encode(iterator_to_array($cursor));

This represents a portion of the retrieved data from the server:

[{
    "_id": {
        "$oid": "609c51803d59e5004f225a92"
    },
    "added_by": "609c35b4f940b04db90a7222",
    "airline_category": "regional",
    ...
}]

On the client side, the variables holding the retrieved data appear as follows:

export default {
  name: 'Seed_Airlines',
  data() {
    return {
        airlineForm:{},
        added_by:'',
        allusersfetched:'',
        airline_name:'',
        ...
        fetchedid:'',
    }
  },

In the mounted section, I execute the following code:

axios.get(fetch_all_airlines)
            .then(response => {   
                console.log(response.data);
                var data = response.data;
                    this.data = data
            })
            .catch(e => {
                this.errors.push(e)
            }); 
    

As the returned data includes a hidden id field:

"_id": {
        "$oid": "609c51803d59e5004f225a92"
    },  

I aim to remove the unnecessary parts "_id": { along with the additional }

leaving only

"$oid": "609c51803d59e5004f225a92"
within the data object.

How can I directly utilize the entire retrieved data object to populate my forms since it aligns perfectly with the initial data structure used to insert entries into mongoDB?

Answer №1

To simplify your code, consider adjusting your data() method to the following structure:

data() {
   return {
       apiData: {
           ...yourListOfPropertiesWillBeHere
       }
   }
}

By organizing your properties in a nested manner, you can prevent Vue from missing any changes. Learn more about change detection caveats here.

When making an API call, use this approach:

axios.get(fetch_all_airlines)
  .then(response => {   
    this.apiData = { ...response.data };
  })
  .catch(e => {
    this.errors.push(e)
  }); 

To remove the _id, implement the following solution:

axios.get(fetch_all_airlines)
  .then(response => {   

    const airlines = response.data.map(value => {
        const airline = return {
            ...value,
            "$oid": value._id["$oid"]
        }
        delete airline._id;
        return airline;
    });

    this.apiData = airlines;

  })
  .catch(e => {
    this.errors.push(e)
  }); 

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

Ways to conceal images until AFTER the completion of the jquery flexslider loading process

After trying to integrate wootheme's Flexslider on my website, I encountered a small issue with its loading process. Whenever the page is refreshed with the slider, there is a brief moment (approximately 1 second) where the first slide appears overly ...

The onclick function is malfunctioning when attempting to use the Windows Phone app in Visual Studio 2015

web development <div class="align_center"> <div class="btn EmployeeloginBtn" **onclick="new Employee().connect()**>CONNECT</div> </div> Employee.js: var Employee = function() { var self = this; self.connect = fu ...

The AJAX success callback function failed to execute in cases where the dataType was set to JSONP during Cross domain Access

type = 'math'; var ajurl = "sample.com&callback=myhandler"; var datas = "cateid=" + cateid + "&type=" + type + "&pno=" + pno + "&whos=" + whos; $.ajax({ type: "GET", url: ajurl, data: datas, contentType: "application/json; ...

What methods are commonly suggested for managing internationalization in Vue.js applications?

Transitioning from Django to vue.js has been a challenge for me, especially when it comes to dealing with translations. In Django, the workflow for adding translations felt intuitive and fool-proof: Annotate code with translation hooks. Pull out translati ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

What steps do I need to take to integrate my RASA assistant into my personal website?

Deploying my rasa chatbot on my live website is my next step. While Rasa worked smoothly on my localhost server, as a newcomer to web development, I found the official guide provided by RASA in the link below a bit challenging to comprehend: The RASA guid ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

The Next.js build process encountered an error when building due to an issue with plotly.js (The build failed with a ReferenceError: self is

Whenever I attempt to build the Next.js app for production using the yarn build command, I encounter the following error. Strangely enough, everything works perfectly fine on the development server when using the yarn dev command. The app employs the react ...

Using Angular.js to fetch information from a MySQL database

I'm currently trying to retrieve data from a MySQL database in an Angular.js application. I have gone through multiple tutorials, but unfortunately, none of them have been successful for me. I have a PHP script that returns a JSON array with example ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Utilizing the power of Vue 2 and NuxtJS to effortlessly customize the appearance of child components

I am currently working on a Nuxt.js project (still using Vue 2) that consists of two components. I am trying to override the child style with the parent's style, but the ::v-deep pseudo selector doesn't seem to be effective. Regardless of my eff ...

Troubleshooting error 422: Fixing issues with Mongoose and Vue

I'm encountering an issue with my API while using express and mongoose to add events to the database. Specifically, I am receiving an error 422 when making the request with axios, however, this error does not occur when using Postman. Just for refere ...

Leveraging both onmouseover and onmouseout for container expansion

My goal is to utilize JavaScript along with the HTML events "onmouseover" and "onmouseout" to create a dynamic container. Essentially, I want the container to act as simply a heading when the mouse is not hovering over it, but expand to display additional ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

jQuery triggers change event twice when radio group is manually modified

After selecting "A&L" in the dropdown menu, the radio group is hidden and its value is changed to "n". I attempted to trigger the change event to make the "Hello" message disappear as well, but it seems to be executing twice - once correctly and then ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Is there a way to utilize the child component's method?

I am looking to access a child component's method from the parent in Vue.js. To achieve this, I plan on using $refs. Code Example: <template> <div>Parent!</div> </template> Script: <script> Vue.component('c ...

What is the reason behind JavaScript objects lacking a toJSON() method?

According to information from http://www.json.org/js.html, JavaScript objects can specify how they are serialized by JSON.stringify() through the use of a toJSON() method. It is interesting to note that numbers and strings appear to have this method, but f ...