如何将对象数组中的元素从api推送到新数组vue.js

时间:2020-04-02 12:10:31

标签: javascript arrays ajax vue.js object

我想将对象数组中的前6个元素推到我刚创建的数组中。 我在网络浏览器上找到了它,但是取而代之的是“ qwe”“ qweqweqwe”,我得到了NaN。为什么?

可以说api中的对象数组如下:

0: {id: 340, name: "qwe", lastname: "qweqweqweq", …}
1: {id: 341, name: "qwe", lastname: "qweqweqweq", …}
2: {id: 342, name: "qwe", lastname: "qweqweqweq", …}
3: {id: 343, name: "qwe", lastname: "qweqweqweq", …}
4: {id: 344, name: "qwe", lastname: "qweqweqweq", …}
5: {id: 345, name: "qwe", lastname: "qweqweqweq", …}
6: {id: 346, name: "qwe", lastname: "qweqweqweq", …}
7: {id: 347, name: "qwe", lastname: "qweqweqweq", …}
8: {id: 348, name: "qwe", lastname: "qweqweqweq", …}

我的代码如下:

.then(response => {
                console.log(typeof response.data, response.data);
                this.model = {
                    name: response.data.name,
                    lastname: response.data.lastname
                }
                this.userInfo.unshift(this.model.name + this.model.lastname); // Here's where i have problem
                if(this.userInfo.length > 6)
                    this.userInfo.pop();
            })
            .catch(error => {
                console.log('Something went wrong', error);
            });
        },

3 个答案:

答案 0 :(得分:0)

如果我理解您的意思,您希望将前6个元素从response推送到userInfo

如果这是您想要的,可以尝试这样:

.then(response => {
    response.data.some((e, index) => {
          this.userInfo.push(e.name + e.lastname)
          return index > 5
    })
})

答案 1 :(得分:0)

这很可能是因为response.data不包含字段namelastname,因为undefined + undefined将导致NaN

答案 2 :(得分:0)

如果您只想移动数组对象的前六个条目,则可以使用此方法

let newArray = response.data.slice(0, 6); // the newArray will have the first six objects of the response data.