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

Despite having Babel Polyfill, Vue is still experiencing compatibility issues with IE11

Regrettably, my most recent project requires support for Internet Explorer 11, which caught me off guard. I've already developed the frontend of the application using Vue.js, while the backend is built with Laravel using laravel-mix/webpack. This is ...

Button is nested within a closing div causing it to trigger independently without affecting the parent

I have implemented a slideup and slidedown system with some fading effects, but I am encountering an issue with the slide up function. It doesn't seem to reset the display property back to none. For reference, here is a Fiddle link: Slide Up/Down Fid ...

Using a loop to iterate through a multidimensional array in Node.js or JavaScript, creating additional data and adding new key-value pairs

Here is an array of objects showcasing different intents and results : var finalresult = [{ "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "data": [{ "intent": "delivery", "result": [{ "h ...

react-native-track-player failing to play song requested from Express server

I set up an expressjs server with a 'songs' route that serves .mp3 files. Here is the code for the Songs Route: import express from "express" const path = require("path") const router = express.Router() ... router.get(" ...

Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue: Access the complete project here: Link to a Plunker example of a log-in screen: http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview (The username and password for this example are both set as "test") Snippet with the error in ...

What is the method for determining the overall page load time of a website, taking into account the total loading time instead of just the document.ready()

I recently attempted to create a function using either JavaScript or Python with Selenium to measure the page load time of a website. While document.ready() gives me the DOM load time, it may not capture AJAX calls that occur afterwards. I noticed there i ...

UI-Router causing issues with AngularJS anchorScroll functionality

Currently, I am utilizing ui-router and attempting to implement automatic scrolling within the controller. However, it seems that anchorScroll function is not working as expected. My assumption is that it may be due to having two '#' symbols in t ...

Building better interfaces with Next.js, Styleguidist, and Fela for React applications

Has anyone successfully set up next.js with Fela and Styleguidist? I'm having trouble linking the Next.js webpack configuration to Styleguidist as mentioned in this article: I've been using this example app: https://github.com/zeit/next.js/tree ...

Error in Nuxt build due to missing core-js dependencies in ./node_modules/bootstrap-vue/:variouspath

After working on my nuxt.js project, I encountered some less-than-friendly error messages. Despite performing a clean install by deleting package.lock and node_modules, as well as installing core-js@2 and @babel/runtime-corejs2, the errors persist. ERR ...

Converting CSV into an Array of Hash Tables

Currently, I am working on parsing a CSV file and creating an array of hashes. While I initially implemented this using my own code, I feel that it may not be the most efficient solution. My aim is to utilize the CSV-Parser library, but so far, I have only ...

Laravel Sanctum - Access Denied post login

My current project is a small web app developed using Laravel 8 sanctum and Vue. I have set up everything on both my local environment and the production server using Docker, ensuring consistency. The application is running smoothly on a subdomain called s ...

Image pop-ups that overlay text on the homepage

I'm facing an issue and I'm looking for a solution... Upon entering my homepage, I would like to display a popup image showcasing a new event so visitors can see it before accessing the website. I attempted to achieve this using JavaScript but w ...

Vercel Next JS features server and client components with distinct timezones

In my Next.js 13.2.4 project, there is a useful helper function named getLocalTime(date) that retrieves the local time of the user's machine in a specific format. //Desired output: 9:30PM export function getLocalTime(date) { const localTime = new D ...

Encountering Timeout Issue Following Laravel 5.6 Framework Update

Yesterday, a strange issue suddenly appeared in my Laravel 5.6 project. It all started after I ran a composer update command. Since then, any Ajax requests to the project API, handled by Axios from a Vue component, are not functioning properly. No CRUD ...

Issue with peculiar circumstances regarding the JSON object and generating a chart, can you pinpoint what's amiss?

When sending data (values and dates) from a hard-coded function, everything works fine - the JSON file is populated and the chart is displayed. However, when I send data from the database, the JSON file is populated but the chart does not appear. Here is ...

How to refresh the javascript cache in Laravel 5.8

I developed a company profile website using Laravel 5.8 and Vue.js to make it reactive, although it's not a single page application (SPA), we can refer to it as a hybrid. The website runs smoothly locally; however, after modifying the JavaScript code ...

Incorporating jQuery into Rails 6.1

I encountered some difficulties while setting up jQuery in rails 6.1, even though I believe it's configured correctly. Below are the steps I've taken: Installed yarn add jquery 2. In config/webpack/environments.js, I made the following changes ...

Providing data in response to a completed form submission

As a beginner, I'm attempting to accomplish the following task: a user selects options from three dropdown menus within a form, and the chosen values are then sent to another file for processing. action="process.php" method="post" In the processing ...

The Quivering Quandaries of Implementing Jquery Accordions

For a demonstration of the issue, please visit http://jsbin.com/omuqo. Upon opening a panel by clicking on the handle, there is a slight jitter in the panels below during the animation. In the provided demo, all panels should remain completely still as t ...

Freezing in IE/Safari due to AJAX jQuery interactions

Feeling frustrated and seeking help. I am currently executing this particular script: <script type="text/javascript" charset="utf-8> jQuery(window).ready(function(){ //alert('running'); var sold = false; var l ...