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

Issue with the usage of section helpers in express-handlebars

I'm having trouble getting the section helper to function correctly. The content of login.hbs was parsed properly, but the js section was not parsed at all. I attempted using helpers within res.render() and directly including section() in engine(), bu ...

The xElement.Descendants method retrieves the concatenated result of the values "falsefalse"

Utilizing the XML document below, I am aiming to regulate the visibility of controls by using boolean values. <?xml version="1.0" encoding="utf-8" ?> <Testy> <Buttons> <boolean>false</boolean> <!-- button1 --> ...

Parsing JSON data into a customized ArrayList in Android

My goal is to extract JSON data into a customized ArrayList containing title and description parameters. Below is an example of the JSON code: [ { "title" : "title1", "description" : "desc1" }, { "title" : "title2", ...

Stylish Wave Animation Effects in CSS for iPad Native Application

The ripple effect on the iPad Native app is malfunctioning. The effect is mistakenly applied to all buttons in the navigation instead of just the li elements. Please identify the error and provide a solution. (function (window, $) { $(function() ...

What is the best way to troubleshoot a $http asynchronous request?

Is there a way to pause the program execution in AngularJS $http call after receiving a successful response? I've attempted to set a breakpoint at that point, but it does not halt the execution. I've also tried using the debugger directive, but ...

When a directive generates an element, the ng-click function may not function as expected

I am developing a custom directive using angularJS. The directive is supposed to replace my custom element with pagination elements. However, the generated elements by the directive contain an ng-click attribute whose value is a function from the controlle ...

Tips for differentiating between elements with identical values in an HTML datalist using Angular

My boss is insisting that I use a datalist in our website interface to select an employee, even though there's no way to determine if the user typed in the name or picked from the list. The challenge is that the list must only display full names, but ...

The Webstorm AngularJS extension appears to be malfunctioning, as it is not able to recognize the keyword 'angular'

As a beginner in Angularjs and web development, I have been using Webstorm to develop my projects. I have already installed the Angularjs plugin, which seems to be working fine in my HTML files. However, I am facing an issue with my .js file. In this file, ...

The process on how to access dynamic object properties within a parent component while using v-for in a child component

I am working on a child component that utilizes v-for to loop through data. Below is the code for the child component: <template> <div> <ul> <li v-for="item in listItems" :key=item.id&g ...

JQuery / Javascript - Mouse Position Erroneously Detected

I'm currently working on developing a drawing application where users can freely draw by moving their mouse over a canvas. My goal is to create a pixel at the precise location where the user drags their mouse. However, I've encountered an issue ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

Display a hidden division when a radio button is selected using Javascript and Jquery

Currently, I am in the process of constructing a form that triggers a series of additional questions based on the selected answer. Below is my current working code snippet: $(".appliedWorked").click(function(){ if($(this).val()==="appliedWorkedYes") ...

Preventing values from being overridden when setting them in a loop using Vue JS and Firebase

After pulling data from Firebase and updating the roomName value in a loop, I'm finding that the updated value is not recognized outside of the loop. Can anyone offer assistance with this issue? export default { name: "Chat", compone ...

Is it possible to pull information from MySQL records using an array?

As I develop my website, I am currently working on implementing a new feature that will enhance its functionality: The feature involves an admin checking a checkbox on a record to indicate that payment has been received. The values related to these paymen ...

Array failing to populate with accurate information

During the loop, I am populating an array: for k in one two three; do array+=( "$k" ) done echo $k[0] # Expecting to print 'one', but prints 'one[0]' echo $k[1] # Expecting to print 'two', but prints 'one[1]' W ...

What is the process for assigning an id to a div in order to make comparisons in React?

After attempting to assign an id to a div for comparison, an error was thrown indicating that "id is not defined". Here is the data: https://i.sstatic.net/PZjDk.png And here is the function: https://i.sstatic.net/y4MEB.png I attempted to add an id attri ...

"Passing the v-model property to a child component in Nuxt.js: A step-by-step

I seem to be having trouble passing dynamically modified properties from layouts into the <Nuxt /> component. This is my ~/layouts/default.vue <template> <div> <input v-model="myprop" /> <span>{{myprop}}< ...

How can you eliminate a specific element from an HTML document?

Utilizing localStorage can be tricky when it comes to keeping the JSON file hidden from being displayed on the HTML page. One approach I used involves sending the JSON file to the client once and then performing all logic using that file. To prevent the JS ...

Querying subdocuments within an array using MongoDB's aggregation framework

Currently, I'm facing a challenge while developing a statistics dashboard for a meditation app. I'm struggling with creating a MongoDB query to fetch the most popular meditations based on user progress. The key collections involved are users and ...