映射React中使用Axios解析的嵌套对象

问题描述 投票:0回答:1

我无法弄清楚如何迭代多个嵌套对象来映射它们。

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”并返回错误。

json reactjs axios
1个回答
1
投票

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.)
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.