简体   繁体   中英

Creating new array of object from api call in react js

I'm actually getting data from google calendar API for public holidays and I want to show them in the calendar. For that, I'm first getting the data from google API, and then I'm trying to create a new array of objects that will store the data that I needed from the google API calendar. The issue is I'm able to create a new array of objects but not able to add new objects for whole the data getting from the google calendar API. I try using loop but not work.

My code

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

})

My console在此处输入图像描述

Data inside google API for reference

在此处输入图像描述

Right now you are looping through the items twice. for loop and map both loop through the array. map is what you want and is used if want to modify an array but it requires that you return each object that you want to place in the new array. You should read about how to use map here array.prototype.map . So I think what you are trying to do is the following:

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) })
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM