首页 > 解决方案 > 在 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”不匹配并返回错误。

标签: jsonreactjsaxios

解决方案


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.)
    });
}

推荐阅读