简体   繁体   English

在axios响应中处理数据

[英]Dealing with data in axios response

I'm new to axios. 我是axios的新手。

In the past when I've made http requests I'm used to getting back an array/array of objects and this allows me to easily format the data how I want by using functions such as map and reduce. 过去,当我发出http请求时,我习惯于找回对象的一个​​数组/数组,这使我可以通过使用map和reduce这样的函数轻松地对数据进行格式化。 I then would render it to the DOM. 然后,我将其呈现给DOM。

I've noticed in the response I get back is an observer object. 我注意到在返回的响应中是一个观察者对象。 How would I go about making the request so it gives me back an array? 我将如何提出请求,以便给我返回数组? What is the standard for dealing with this observer object? 处理此观察者对象的标准是什么?

getSomething (myId) {
    return axios.get('/api/getSomething', {params: {'id': myId}})
                .then(response => console.log(response.data))
                .catch((promise) => this.handleError(promise));
}

Thanks 谢谢

EDIT: Updated code. 编辑:更新的代码。 To clarify, when I call getSomething() response.data is an object even though I am sending it as an array on the backend. 为了澄清,当我调用getSomething()即使我将其作为数组在后端发送,它也是一个对象。 I am assuming that axios is changing this array to an object. 我假设axios正在将此数组更改为对象。 The object has a bunch of extra properties like __ob__ and get 0 该对象具有许多额外的属性,例如__ob__get 0

So I found the issue. 所以我找到了问题。 If you pass through an array where the keys are not in order eg [1: [], 5: [], 6:[]]. 如果通过键不按顺序排列的数组,例如[1: [], 5: [], 6:[]]. Javascript will change it into a observer object which has different properties in order to maintain the keys. Javascript会将其更改为具有不同属性的观察者对象,以维护键。 This issue is not related to axios. 此问题与axios无关。

You can do something as simple as the following to access the data: 您可以执行以下操作来访问数据:

axios.get('/some/url').then(response => {
    console.log(response);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM