2

I'm trying to add elements from json response to my existing array by clicking on a button but I have a problem with adding these elements properly.

Here I have an empty array called results where I'm storing my data from response.

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

This is my method for getting 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'm adding response data to array like this:

vm.results += response.data.data;

My respose is correct but after this operation my results array look like: "[object Object],[object Object]..."

I have also tried to add new elements by push method:

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

But then, elements are added in new arrays but I want to add objects to existing array.

Here is the structure of my 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...]

3 Answers 3

8

Try :

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

This will append the array "response.data.data" to the "results" array.

Sign up to request clarification or add additional context in comments.

1 Comment

Of course that works - that's what Array.prototype.concat() was designed for. The more modern, preferrable approach in case you have a Babel transpilation in your build process though is using the spread operator .... You better get used to it, you gonna see this everywhere soon.
7

First of all you don't have to use var vm = this;, this.results will work even in your axios (and every other) callbacks in the context of a vue component.

But the actual problem is that you are using the concatenation += operator to add to an array. Simply use push with the spread operator (...) instead and it should work.

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

})

6 Comments

That would make him push an array into his existing array, instead of pushing those elements in his response array.
@connexo My bad, didn't see the response data was an array. You can still do it with the spread ... operator though.
Yeah, as @connexo said, it would create new arrays into my existing arrays. What do you mean by spread operator? And I have checked that I still have to use this vm variable instead of this inside axios.
@VividDreams The spread operator always gets lots of confusion. It is literally three dots, so the ... is part of the code. It takes the content from an object (or array) and spreads it out, so basically pushes every element of the incoming data into the results array. It is super useful in many situations, you can check out the documentation here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
this.results.push(...response.data.data); will not work for two reasons: push expects a single array element and adds that after the end of the array it is called on. this is not what you are expecting here, you either have to use arrow syntax .then((response ) => {/*whatever*/}) or use Function.prototype.bind() method like .then(function (response) { /*whatever*/ }.bind(this))
|
0

ES6 way of doing this is using the spread operator ...:

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

// use JSON.stringify so you don't see [Object object] when console logging
console.log('[...a, ...b]' + JSON.stringify([...a, ...b]))

When used on an array ...arr it means give me all elements in arr here, when used on an object ...obj it means give me a shallow copy of all enumerable properties of obj.

Just to prove it works with your case:

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]))

5 Comments

Ok, but how to use it in this specific case? results = [...results] + JSON.stringify({...response.data.data}) is not working. What am I getting wrong?
results = [...results, ...response.data.data] The call to JSON.stringify is only for logging (so you see a proper textual representation of the contained objects), not for your real code.
Ok, thank you. I don't have babel set up, so I can't check right now if this one works or not. Not working in chrome and according to specs it should work on chrome without babel. It gives me an empty array.
That is not due to the spread operator then, there's got to be something else that ruins it. Also, with any vue template, you have Babel setup included already. Don't use the <script src="/path/to/vue.min.js"> version of Vue, you're missing out on the best part of Vue then.
Added an example based off your sample data given to prove it works. I recommend you try to identify the error in your code giving you an empty array just for practice reasons - it might help you understand the spread operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.