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 the `preventDefault` method within an `onclick` function nested inside another `onclick

I am currently working on an example in react.js <Card onClick="(e)=>{e.preventDefault(); goPage()}"> <Card.body> <Media> <img width={64} height={64} className="mr-3" ...

How can you provide arguments to a mock function?

While using jest for unit testing, I am encountering the following line of code: jest.mock('../../requestBuilder'); In my project folder, there is a __mocks__ subfolder where I have stored my mock requestBuilder.js file. The jest unit test i ...

Running the JavaScript code on a webpage using Selenium WebDriver

I am currently in the process of creating an automated test for a website, and I am encountering some difficulty trying to execute a specific function within the site's code. Upon inspecting the developer tools, I have identified the function I need ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

Using AJAX to Send Requests to PHP

Embarking on my first ajax project, I believe I am close to resolving an issue but require some guidance. The webpage file below features an input field where users can enter their email address. Upon submission, the ajax doWork() function should trigger t ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

Unlock the power of viewing numerous inputs simultaneously

Seeking guidance on how to allow users to preview images before uploading them. Currently, my code successfully previews images for one input field, but I am facing challenges when trying to add multiple pairs of inputs and images. How can I implement mul ...

Launch a new tab within the parent window, passing on variables from the parent window

Currently, I have a button that opens a new window in a new tab by using window.open("newpage.html"). In the child window, I use childVar = window.opener.parentGlobalVar to access global variables from the parent window. Now, I have been requested to open ...

Present a Java-generated JSON object on a JSP page using JavaScript

Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see th ...

Hidden form in JavaScript does not submit upon clicking the text

My previous question was similar to this but with a smaller example. However, the issue with that code differs from my current code. (If you're curious, here's my previous question: JavaScript Text not submitting form) Currently working on my fi ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

Begin composing in Excel

I am looking to manipulate an existing Excel file by writing values from an array and closing it all on the client side. Here is the code snippet I have been using: for (var c=0; c<arrMCN.length; c++) { var mcnCreate = arrMCN[c]; var mcnNumber =mcnCre ...

Make sure that the parent element is only visible once all of its child elements have

As a newcomer to the world of react, I am facing some challenges. I have created a form in react which includes a dropdown. To ensure reusability across multiple pages, I decided to turn this dropdown into a component that is responsible for fetching all n ...

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Tips on retrieving an item using jQuery's select2 plugin

How can I retrieve the value (flight_no) from the processResults function in order to populate the airline name with the respective flight number when selected? I've attempted to access the (flight_no) within the processResults function, but I'm ...

Have you ever wondered why the React HeroIcons architecture includes React.createElement instead of simply returning plain SVG elements?

As I integrate HeroIcons into my Next.Js app, I find myself pondering over how they have structured their package architecture. The way they return icons is like this: const React = require("react"); function ArchiveIcon(props, svgRef) { retur ...