reactjs - Axios 参数返回对象内部的数据而不是数组
问题描述
当使用不带参数的 axios.get 时,所有数据都像预期的那样在数组内部返回,但是当我使用参数时,所有对象都在对象内部返回并且我无法映射它。如何将所有对象放入数组中?如果我尝试将它放在数组中,它只会放置包含我需要的所有对象的对象。
axios.get('http://api.digiart.lt/items/',
{ params:
{ category:"latte" }} )
.then(response => {
let coffee = response.data;
this.props.onLoadData(coffee);
console.log(response.data);
像这样返回
{…} 项:对象{0:{...},2:{...},3:{...},...}:对象{...}
应该是这样的
数组 (41) [ {…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、{…}、…]
解决方案
http://api.digiart.lt/items/
这是来自API的默认响应
用于Object.keys
将其映射到数组。
// Request -> http://api.digiart.lt/items?category=latte
var response = {
"items": {
"0": {
"title": "Abbey's White Chocolate Latte",
"description": "I created this recipe for my little sister, Abbey, who`s a latte fanatic. She was blown away, and drained it to the last drop! This makes one VERY large, indulgent latte, and could probably serve two. Enjoy!\n\nIngredients:\n1 1\/2 cups milk\n1 tablespoon heavy cream\n1\/8 teaspoon vanilla extract\n1 tablespoon white sugar\n1\/2 cup brewed espresso\n1\/4 cup white chocolate chips, chopped",
"url": "https:\/\/www.allrecipes.com\/recipe\/137332\/abbeys-white-chocolate-latte\/",
"category": "latte",
"date": "2018-05-31",
"img": "https:\/\/images.media-allrecipes.com\/userphotos\/560x315\/2107268.jpg"
},
"2": {
"title": "Brown Sugar-Caramel Latte",
"description": "Sometimes coffee is a dessert in itself. This is one of my favorite morning treats to make a Monday seem less intimidating. You'll need a battery-powered milk frother or it's just not the same.\n\nIngredients:\n1 tablespoon brown sugar\n1\/4 cup half-and-half\n1 tablespoon caramel ice cream topping\n3\/4 cup hot, brewed coffee",
"url": "https:\/\/www.allrecipes.com\/recipe\/139119\/brown-sugar-caramel-latte\/",
"category": "latte",
"date": "2017-08-22",
"img": "https:\/\/images.media-allrecipes.com\/userphotos\/560x315\/707064.jpg"
}
// .. More items
}
}
var arr = []
Object.keys(response.items).forEach(key => arr.push(response.items[key]))
console.log(arr)
推荐阅读
- php - 为什么我的 ajax 请求不发送到书面 url?
- python-3.x - 我应该学习哪些库和概念来解析网页中的数据?
- python - ValueError: X 必须是 NumPy 数组
- docker - 存储在主机上的 Docker 映像的位置不存在
- smallbasic - 是否可以同时打开 Textwindow 和 Graphicwindow?
- python - 如何在 Python 中按升序读取和写入文件中的值?
- input - 我无法获得将 Y 定义为上层的输入(为是)我得到一个回溯调用
- counter - 使用 LPTIM 在 STM32 上进行频率测量
- algorithm - 无限时间后在矩阵中寻找水的算法
- android - 如何从资产文件夹在webview中加载pdf