Adding objects to an existing array in Vue.js can be a seamless and

Struggling to populate my existing array with elements from a JSON response using a button click. The issue lies in properly adding these elements to the array.

I have an empty array named results where I store the data from the response.

export default {
  name: 'Posts',
  props: ['user_id'],
  data: function(){
      return{
          results: [],
          pageNumber: 1,
      }
  },.....

This is the method I use to fetch the data:

getData: function () {

    var vm = this;

    axios.get('http://127.0.0.1:8000/api/posts?page=' + vm.pageNumber)
    .then(function (response) {
        vm.results += response.data.data;

    })
    .catch(function (error) {
    });

},

In this method, I am appending the data from the response like this:

vm.results += response.data.data;

The response is correct, but after this operation, my results array looks like: "[object Object],[object Object]..."

I also attempted to add new elements using the push method:

vm.results.push(response.data.data);

However, this adds objects to new arrays rather than the existing one.

Here is the structure of the response:

{"current_page":1,
"data":[
{
"id":60,
"title":"Post 1",
"body":"Post 1 body",
"created_at":"2018-06-09 18:33:40",
"updated_at":"2018-06-09 18:33:40",
"user_id":8
},
{
"id":61,
"title":"Post 2",
"body":"post 2 body",
"created_at":"2018-06-09 18:33:40",
"updated_at":"2018-06-09 18:33:40",
"user_id":8
},
etc...]

Answer №1

Consider using the following code snippet:

vm.results = vm.results.concat(response.data.data);

By utilizing this method, you can easily append the contents of the "response.data.data" array to the existing "results" array.

Answer №2

First and foremost, there is no need to declare var vm = this;. Using this.results directly will function properly within axios (and other) callbacks when working with a vue component.

The main issue lies in the usage of the concatenation operator += to add to an array. Instead, use push with the spread operator (...) and that should resolve the problem.

axios.get('http://127.0.0.1:8000/api/posts?page=' + this.pageNumber)
.then(response => {
    this.results.push(...response.data.data);
})

Answer №3

One way to accomplish this in ES6 is by utilizing the spread operator ...:

let a = [{name: 'Peter'}]
let b = [{name: 'Joanna'}, {name: 'Steven'}]

// Use JSON.stringify when logging to avoid [Object object] display
console.log('[...a, ...b]' + JSON.stringify([...a, ...b]))

When applied to an array ...arr, it means include all elements in arr here. When used on an object ...obj, it indicates create a shallow copy of all enumerable properties from obj.

To demonstrate its functionality with your specific scenario:

let origArr = [{
    "id": 58,
    "title": "Post 1",
    "body": "Post 1 body",
    "created_at": "2018-06-09 18:33:40",
    "updated_at": "2018-06-09 18:33:40",
    "user_id": 8
  },
  {
    "id": 59,
    "title": "Post 2",
    "body": "post 2 body",
    "created_at": "2018-06-09 18:33:40",
    "updated_at": "2018-06-09 18:33:40",
    "user_id": 8
  }
]
let response = {
  data: {
    "current_page": 1,
    "data": [{
        "id": 60,
        "title": "Post 1",
        "body": "Post 1 body",
        "created_at": "2018-06-09 18:33:40",
        "updated_at": "2018-06-09 18:33:40",
        "user_id": 8
      },
      {
        "id": 61,
        "title": "Post 2",
        "body": "post 2 body",
        "created_at": "2018-06-09 18:33:40",
        "updated_at": "2018-06-09 18:33:40",
        "user_id": 8
      }
    ]
  }
}

console.log(JSON.stringify([...origArr, ...response.data.data]))

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 Vue Carousel Sliding Functionality

I'm currently tackling a project that involves incorporating Vue Carousel for displaying product slides with both images and text on each slide. My goal is to have only 5 slides displayed per page, complete with navigation arrows and the ability to dr ...

Updating className in React by responding to button clicks without relying on numerous conditional statements

I've been working on a small project for the past few weeks. The main idea is to have a stepper with different steps that the user can click on to see their tasks for each step. There is also a completion button for each step, but I'm struggling ...

Tips for making WebDriver pause until Sencha AJAX request finishes

While testing a page with Selenium WebDriver, I encountered an issue related to the Sencha JavaScript library being used on the underlying page. The problem arises when I input a value into a field and an AJAX call is made to validate that field. If the va ...

What is the best way to initiate a saga for an API request while another call is currently in progress?

During the execution of the first action in saga, the second action is also being called. While I receive the response from the first action, I am not getting a response from the second one. this.props.actions.FetchRequest(payload1) this.props.actions.F ...

Angular 2: A Beginner's Guide to Creating Objects and Transforming Code from Angular to Angular 2

Currently, I am learning Angular 2 and facing an issue. I am unsure about how to create an object in my login function (Angular1). public logIn() { let phone = this.user.number.replace(/\s+/g, ''); let email = 'u&a ...

Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as w ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

If an Angular reactive form component has a particular value

I am working with a group of radio buttons. When a user chooses the option "yes," I would like to display an additional input box on the form. Link to Code Example HTML.component <div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt- ...

React - CSS Transition resembling a flip of a book page

As I delve into more advanced topics in my journey of learning React and Front Web Dev, I discovered the ReactCSSTransitionGroup but learned that it is no longer maintained so we now use CSSTransitionGroup. I decided to create a small side project to expe ...

The jQuery AJAX request is not returning a truthy value when parsing

On my website, I am dealing with a large form and using the serialize() method to process it. However, I have encountered an issue: After completing the form, the result always returns false. I checked this using Firebug. Even though data.ok == true has ...

Retrieve the JSON data embedded within the HTML source code and utilize its contents

I stumbled upon a URL like http://example.com. Taking a look at the HTML source, it appears as follows: <html> test test2 {"customer":{"email":null,"is_eu":true"} t </html> My goal is to extract the JSON data from this source and then manipul ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...

What is the best method for selecting or isolating the code for a single animation created using JavaScript?

Currently, I am attempting to extract the CSS and JS code of an image reveal animation that is part of a static HTML page: https://i.stack.imgur.com/bnmaO.gif The challenge lies in the fact that the desired effect is one among many showcased image animat ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Failed to execute npm script for server side rendering (ssr)

I experimented with Server-Side Rendering (SSR) in my React application for SEO benefits. Although I encountered certain errors, they were not considered actual errors by React. Initially, the error appeared in componenDidMount=()=> Upon commenting ou ...

Convert a tuple into a JSON string

Looking to serialize a tuple into JSON: List<Tuple<string, string, string, string, string, string>> iCalEvents = new List<Tuple<string, string, string, string, string, string>>(); When I use the following code to output the value: ...

What is the best way to create a toggle button that can show more or show less of a text snippet with animation?

Is it possible for someone to assist me with showing a long text partially and providing a "show more" button to reveal the rest, along with a "show less" option, all with some CSS animation? I was thinking of using a font awesome arrow down icon for expan ...

Observables do not provide any results when used in a pipe with an image src

I recently created a custom pipe for the image src in my application: It is applied to selectors like this: <img [src]="myobject?.URL | secure" /> Here's the code snippet for the pipe: import { Pipe, PipeTransform } from '@angular/c ...

Posting several pictures with Protractor

In my test suite, I have a specific scenario that requires the following steps: Click on a button. Upload an image from a specified directory. Wait for 15 seconds Repeat Steps 1-3 for all images in the specified directory. I need to figure out how to up ...

Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit. However, I encountered an issue where the custom validator was not r ...