我无法弄清楚如何迭代多个嵌套对象来映射它们。
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.)
});
}