Unable to add an item from an array to the data property in Vue.js

When fetching data from Laravel, I use the following response:

$unserialize = unserialize($import->field_names);
return response()->json( $unserialize, 200 ) ;

On Vue JS, I can view the response using:

console.log(response); 

The data is displayed in an array format (Check the red arrow mark):

https://i.sstatic.net/qh9Ik.png

I have an empty options array property defined as follows:

options : []

To add object data to this array with a key value and text, where the value will be each item of the response data, I am using the following code snippet:

response.data.forEach((item, index) => {
    this.options.push({
        value: item,
        text: index
    });
});

However, when I console log

console.log(this.options);

I do not see an array of objects in the options property. Instead, I see this:

https://i.sstatic.net/eP3bg.png

Can you explain why? I expect the options should store items like this:

options: [
    { value: null, text: 'Please select some item' },
    { value: 'a', text: 'This is First option' },
    { value: 'b', text: 'Default Selected Option' },
    { value: 'c', text: 'This is another option' },
    { value: 'd', text: 'This one is disabled', disabled: true },
] 

Update:

Console.log(response);

https://i.sstatic.net/vrG8e.png

Answer №1

It seems like the issue might involve the utilization of this keyword.

To address this, consider adjusting your code as follows:

this.options = [...this.options,
                ...response.data.map((item, index) => 
                     ({
                        value: item,
                        text: index
                      })
                )]

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

Issues with JavaScript causing YouTube embed player to malfunction

For the past few days, I've encountered an issue where my JavaScript code to embed YouTube videos isn't working properly. The video loads but it's not playable as the play button is unresponsive. The console shows this error: Uncaught TypeE ...

Automatically adjusting the locale settings upon importing the data

Is there a way to create a dropdown menu of languages where clicking on one language will change the date format on the page to match that country's format? In my React app, I am using moment.js to achieve this. My plan is to call moment.locale( lang ...

What is the best approach for finding the xPath of this specific element?

Take a look at this website Link I'm trying to capture the popup message on this site, but I can't seem to find the element for it in the code. Any ideas? ...

Encountering the error "Invalid URL. Please provide only absolute URLs" while trying to integrate the Airtable JavaScript library in a Next.js application

I am currently working on a Next JS application that includes a Page called somePage.js. In this page, I am attempting to make an XHR request to the Airtable API from within the getServerSideProps function. The relevant components look like this: pages/so ...

"Discover the step-by-step process of transforming an input field value into a checkbox with

I've been experimenting with creating a To-Do list using HTML, CSS, and Javascript. I've managed to capture the input field value in a fieldset so far. However, my goal is to find a way to transform the input field value from the textfield into a ...

Sending information to a child component causes the parent's data to be modified as well

Transferring information from the parent to the child component has always been easy for me. However, I recently encountered an issue where updating the data in the child component also updates the data in the parent component simultaneously. Now, I am loo ...

Using Ajax to retrieve information from a database and bringing it back

I'm currently working on implementing an Ajax request that can retrieve data from the database in the controller and return it. Here's the code I have in the view: $(".btn-submit").click(function(e) { e.preventDefault(); var name = $("in ...

Javascript - Button animation malfunctioning after first click

One issue I'm facing is with an animation that is triggered using the onmousedown event. Another function is supposed to stop the animation when onmouseup is detected. The problem arises after the first time it works correctly. Subsequent attempts to ...

Display div - conceal div - pause for 15 minutes - continue the cycle

I have a challenging JavaScript task that I've been struggling with for quite some time. The goal is to display a div for 5 seconds, hide it, wait for 15 minutes, then show it again for another 5 seconds, and continue this process in an infinite loop. ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

Using jQuery to show an Ajax loader while the page is loading

Is it possible to display a loader (gif) before the HTML is loaded and during a page transition? I have seen this type of effect on many websites and am curious if it can be implemented. If so, is it achievable using jQuery, AJAX, and PHP? I know how to ...

How do you transform data stored in map to string format?

The main objective is to take a large txt file and replace all words according to the information in a csv file. This process will generate a new txt file as well as a new csv file that shows the frequency of each word. I'm currently struggling with ...

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

What are the steps for incorporating more intricate validation criteria?

I would like to enhance the validation in this code by ensuring that the zip code field contains 5 digits that are only numbers, and the phone number field has at least 10 digits with no letters except for () or -. How can I incorporate this additional v ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...

Learn the steps for generating an array of objects in AngularJS or JavaScript

I have an array named $scope.data2 and I am looking to create another array of arrays based on the data provided below: $scope.data2 = [ {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 12:30 PM" ...

Establishing restrictions for a particular subset of an array in x0 using the scipy library in Python

Trying to assign unique boundaries for each subset of the x0 array in the scipy.optimize.minimize() function. Here is what has been attempted: x0 = np.zeros(20) # disp = x0[0:5] # w = x0[5:10] # qi = x0[10:15] # qai = x0[15:20] ...

Tips for extracting data from cells within an HTML table using JavaScript

I am looking to extract the values from a cell of an HTML table in order to store them in a MySQL table using PHP. I prefer to utilize JavaScript instead of jQuery. I have assigned a unique ID to each TR based on the ID field in the MySQL table. Additiona ...

What is the method for obtaining the values from these newly generated text fields?

Every time I click on the "ADD TEXTBOX" button, a new HTML textbox is dynamically created using jQuery's append method. However, I am struggling to figure out how to retrieve and store the values of these textboxes in PHP. $(w).append('<div&g ...

Linking two socket.io clients together (Establishing a direct socket-to-socket connection that works across different browsers)

Can a direct P2P connection be established between two browsers using socket.io-client, bypassing the node.js server they are currently connected to? If possible, how? The goal is for clients A and B to communicate directly without going through the node. ...