javascript Vue.js 将对象添加到现有数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50783808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:16:42  来源:igfitidea点击:

Vue.js add objects to existing array

javascriptarraysjsonobjectvue.js

提问by VividDreams

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.

我正在尝试通过单击按钮将 json 响应中的元素添加到我现有的数组中,但是我在正确添加这些元素时遇到了问题。

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

在这里,我有一个名为 results 的空数组,我在其中存储来自响应的数据。

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;

vm.results += response.data.data;

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

我的响应是正确的,但在此操作后,我的结果数组如下所示:“[object Object],[object Object]...”

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

我还尝试通过 push 方法添加新元素:

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

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

回答by JeffProd

Try :

尝试 :

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

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

这会将数组“response.data.data”附加到“results”数组。

回答by Philip Feldmann

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

首先,您不必使用var vm = this;,this.results甚至可以在 vue 组件上下文中的 axios(和其他所有)回调中工作。

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

但实际问题是您正在使用连接+=运算符添加到数组中。只需push与扩展运算符 ( ...) 一起使用,它就可以工作。

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

})

回答by connexo

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

ES6 这样做的方法是使用扩展运算符...

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 ...arrit means give me all elements in arrhere, when used on an object ...objit means give me a shallow copy of all enumerable properties of obj.

当在数组上使用时,...arr它意味着给我arr这里的所有元素,当在一个对象上使用时,...obj它意味着给我的所有可枚举属性的浅拷贝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]))