json - 在 React 中映射使用 Axios 解析的嵌套对象
问题描述
我不知道如何遍历多个嵌套对象以 .map 它们。
JSON 目前看起来像:
"results": [
{
"cars": [
{
"brand": "BMW",
"model": "430i",
"is_onsale": false
},
{
"brand": "BMW",
"model": "540i",
"is_onsale": true
}
]
}
]
我正在使用 axios 从 URL 获取数据,并尝试在控制台中显示它:
componentDidMount(){
axios.get('https://randomapi.com/api/****')
.then(json => json.data.results.map(result => ({
brand: result.cars.brand,
model: result.cars.model,
status: result.cars.is_onsale
})))
.then(newData => console.log(newData));
}
然后返回 undefined 所有值。
当我更改为 .cars[x] 时,我可以获得该特定数组索引的值:
brand: result.cars[0].brand,
model: result.cars[0].model,
status: result.cars[0].is_onsale
如何遍历所有内容并存储它们,一个简单的 for 循环似乎与“.then”不匹配并返回错误。
解决方案
results
是一个数组。数组中的每个条目都有自己的数组cars
。
从您在问题下方评论中的回答来看,听起来您想将所有这些cars
数组组合成一个数组,尽管它们在结果中是单独的数组(可能是有原因的)。如果是这样,您可以遍历结果并将每个结果cars
数组中的条目添加到单个组合cars
数组中。例如:
componentDidMount(){
axios.get('https://randomapi.com/api/****')
.then(json => {
const cars = [];
json.data.results.forEach(result => {
cars.push(...result.cars);
});
return cars;
})
.then(allCars => {
// do something with all the cars
})
.catch(error => {
// do something with the error (report it, etc.)
});
}
或者,像几乎所有的数组操作一样,你可以把它硬塞进 reduce
,但它不是很清楚并且会生成很多不必要的临时数组:
componentDidMount(){
axios.get('https://randomapi.com/api/****')
.then(json => json.data.results.reduce((all, result) => all.concat(result.cars), []))
.then(allCars => {
// do something with all the cars
})
.catch(error => {
// do something with the error (report it, etc.)
});
}
推荐阅读
- aurelia - 如何在 aurelia slickgrid/slickgrid 中的 cloumn 值旁边显示图标?
- ios - Sentry iOS dSYM:无法处理本机堆栈跟踪
- android-studio - Android Studio 显示当前用户的帖子以及其他用户的帖子
- python - python - 如何在python的Plotly图表中获取滑块的位置?
- python - 将输入(字符串)视为 python 中的列表
- image-processing - 如何使用 4 个通道而不是 3 个通道在 Halide 中加载图像()?
- java - 在对 Dataframe 执行操作时引发 sqlContext 异常
- flutter - 在 Flutter 的状态类中调用变量的问题
- java - Webdriver在硒中打开太多浏览器
- discord - 从用户 ID 获取用户活动 - Discord.py