在 React js 中从 api 调用创建新的对象数组

Creating new array of object from api call in react js

我实际上是从 google 日历 API 获取 public 假期的数据,我想在日历中显示它们。为此,我首先从 google API 获取数据,然后尝试创建一个新的对象数组来存储我需要的 google 数据API 日历。问题是我能够创建一个新的对象数组,但无法为从 google 日历 API 获取的整个数据添加新对象。我尝试使用循环但不起作用。

我的代码

let google;

useEffect(() => {
    axios.get('https://www.googleapis.com/calendar/v3/calendars/en.australian%23holiday%40group.v.calendar.google.com/events?key=personalkey')
        .then(res => {
            const data = res.data.items;
            console.log("Google api calendar data", data)

        for (let i = 0; i < data.length; i++) {

            data.map((item) => {
                google = {
                    "id": item.id,
                    "title": item.summary,
                    "location": "Australia",
                    "start": new Date(moment(item.start.date)),
                    "end": new Date(moment(item.end.date)),
                    "description": item.description,
                    "durationday": 'Fulllday',
                    "sameId": null

                }
            })
        }

        console.log("goggle making array of object inside promise", google)
    })
    .catch(err => { console.log('Google api calendar error', err) })

})

现在您正在循环遍历项目两次。 for 循环和 map 都循环遍历数组。 map 是您想要的,如果要修改数组则使用它,但它要求您 return 每个要放置在新数组中的对象。您应该在此处阅读有关如何使用地图的信息 array.prototype.map。所以我认为你正在尝试做的是以下内容:

useEffect(() => {
  axios.get('https://www.googleapis.com/calendar/v3/calendars/en.australian%23holiday%40group.v.calendar.google.com/events?key=personalkey')
    .then(res => {
        const data = res.data.items.map((item) => {
          return {
            "id": item.id,
            "title": item.summary,
            "location": "Australia",
            "start": new Date(moment(item.start.date)),
            "end": new Date(moment(item.end.date)),
            "description": item.description,
            "durationday": 'Fulllday',
            "sameId": null
          }
      })
    console.log("Your new array of modified objects here", data)
  })
  .catch(err => { console.log('Google api calendar error', err) })
}, [])