Guide on inserting a new column into an array of objects in Vue

Below is the fetch method I have defined to retrieve recordings from the database. However, I need assistance in adding a new column to each record specifically for frontend purposes. Can someone help me with this problem?

<script>
  export default {
    components: {
    },
    data: function() {
      return {
        versions: [],
      };
    },
    created: function() {
      this.fetchVersions();
    },
    methods: {     
      fetchVersions() {
        var that = this;
        var url = '/area/versions.json';

        this.$axios.get(url)
        .then(response => {
          that.versions = response.data;
        })
      },

    }
  };
</script>

The current structure of the versions array is as follows:

versions: [
  {    
    name: 'Version 1',
    region: 'CBA 09',
  },
  {
    name: 'Version 2',
    region: 'CBA 11',
  }
]

I would like to include a new column at the beginning of each record with the same value, similar to this example:

versions: [
  {  
    manager: '0024',
    name: 'Version 1',
    region: 'CBA 09',
  },
  {
    manager: '0024',
    name: 'Version 2',
    region: 'CBA 11',
  }
]

Answer №1

To achieve this, you can leverage the map function along with a destructuring assignment (...):

this.list = response.data.map(item => ({...item, category: '0045'}));

Additonally, there is no requirement for the use of that, as arrow functions encapsulate the parent scope.

See an example in action below:

const listItems = [
  { title: 'Item A', type: 'Type 1' },
  { title: 'Item B', type: 'Type 2' }
];

console.log( listItems.map(item => ({...item, category: '0045'})) );

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

Using VueJS to add a class to one element based on the presence of a specific class on another element

I'm currently working with VueJS and I'm facing a challenge in binding a class to one element based on the existence of a class on another element. This function is implemented within a :for loop to iterate through and display a list. The ' ...

When attempting to run JavaScript within PHP, an Uncaught SyntaxError is encountered

When I run this code without PHP, it works perfectly. <?php $activeStatus = "$getuser[active]"; if($activeStatus == 1) { echo '<script type="text/javascript">'; echo ' $(document).ready(function () { v ...

Creating a unique custom error message for every validation option

I am using a Joi schema and I would like to set custom error messages for each validation option. Here is an example of my schema: const schema = Joi.object().keys({ name: Joi.string() .min(5).error(() => 'first message') .ma ...

Utilizing PHP, Javascript, and jQuery in mobile technology gadgets

Can anyone recommend mobile technology products that have been developed using PHP, Javascript, and jQuery? What are the newest mobile products available on the market that have been built using these languages? Do popular devices like iPhone, BlackBerry ...

The issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

Obtain elements from a nested array in JSON format

While working on HTML elements within the "Test" object, I am creating individual elements for each object. These objects can be either type:block or type:list and may contain an array named "List" when they are of type:list. I aim to generate an HTML ".p ...

What is the best approach for overlaying random meshes onto a terrain using a heightmap in three.js?

I'm interested in plotting randomly generated meshes at the y-position that corresponds to the terrain's height in three.js. While browsing through the documentation, I came across the raycaster method, which seems like it could be useful. Howeve ...

Retrieving Array keys from PHP using jQuery

As a beginner in jQuery, I am eager to learn how to retrieve Array keys from a php file using jQuery. Currently, I have jQuery code set up to send input to file.php and execute a query on every keyup event. When file.php echoes the result, it looks somet ...

Accessing CouchDB using AngularJS requires users to sign in, with the authentication cookie only being sent to the `/_

Check out my previous posts on this topic here: 1, 2 I currently have an AngularJS app with two controllers. The first one interacts with CouchDB documents, while the second handles sign-in requests to example.com/demo/_session. Upon opening the applicat ...

Decoding JSON data using Gson

Here is some JSON data I am working with: { "boards": [ { "board": "3", "title": "3DCG", "ws_board": 1, "per_page": 15, "pages": 11 }, { "board": "a", "title": "Anime & Manga", ...

What is the reason behind the brute force method for finding the maximum sum subarray having a time complexity of

The concept of finding the maximum subarray sum is a well-known issue within the realm of computer science. There exist at least two potential solutions: One method involves brute force, where all possible subarrays are calculated to determine the maximu ...

Creating personalized headers for WebSocket in JavaScript

I am currently in search of a straightforward method to utilize WebSocket with custom headers for a web application, utilizing PHP as the backend and js+vuejs for the frontend. My application needs to establish a connection with a WebSocket server based o ...

Utilizing pointers with character arrays in string manipulation

After spending hours reading, the concept of conversions between { char i ="adf"; char foo[]; char bar[256]; } along with using * and & has left me more confused than ever. I have managed to get some code working. int TX_SEND(char send ...

Issue with sending data to the server via API using AngularJS controller

I am a beginner in angular js and I am attempting to POST data to the server using an API that I have created: function addmovie_post() { { $genre = $this->post('genre'); $cast = $this->post('cast'); $director ...

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 ...

What is the proper placement for index.html <head/> class helper functions within a ReactJS Component?

My custom helper functions are stored in a JavaScript file called classie.js: ( function( window ) { 'use strict'; function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, ...

Eliminate duplicate entries in typeahead.js by ensuring unique data sources for both prefetch and remote

Currently, I have implemented typeahead.js with both prefetch and remote data sources. You can check out the example here. $(document).ready(function() { var castDirectors = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('val ...

Loading Bootstrap accordion content with AJAX only when clicked

Is there a way to load ajax content into an accordion only when it is active? This could help prevent unnecessary data loading. It would be helpful to have a spinner displayed while the content is loading. I've searched online but haven't found a ...

Incorporate additional plugins into React-Leaflet for enhanced functionality

I'm currently working on developing a custom component using react-leaflet v2, where I aim to extend a leaflet plugin known as EdgeMarker. Unfortunately, the documentation provided lacks sufficient details on how to accomplish this task. In response, ...

Creating dynamic images in JavaScript by assigning URL paths from string variables

Currently, I am utilizing JavaScript to parse through an XML file. One interesting aspect of the XML is that it contains URLs which link to images like this one: http://localhost/pic.jpg Throughout the parsing process, I am storing each URL as a string va ...