首页 > 解决方案 > 在谷歌日历 API 中访问“忙碌”数组

问题描述

尝试在 Google Calendar API 中使用freebusy查询。我按照Googleapis 文档中提供的示例进行操作,确实得到了结果,但忙碌信息仅显示为[Array],没有实际的忙碌信息。

代码(只是相关部分):

const res = await calendar.freebusy.query({
        requestBody: {
            timeMin: (new Date()).toISOString(),
            timeMax: '2021-03-25T23:00:00+01:00',
            items: [
                {
                   id: 'calendarid'
                }
            ]
        },
    });

    console.log(res.data);

获得正确的响应(意味着没有错误),但响应始终将“忙碌”属性显示为 [Array]:

{
  kind: 'calendar#freeBusy',
  timeMin: '2021-03-20T10:39:42.000Z',
  timeMax: '2021-03-25T22:00:00.000Z',
  calendars: {
    'calendarid': { busy: [Array] }
  }
}

正确的完整结果(使用Google API Explorer测试):

{
 "kind": "calendar#freeBusy",
 "timeMin": "2021-03-20T11:00:00.000Z",
 "timeMax": "2021-03-25T22:00:00.000Z",
 "calendars": {
  "calendarid": {
   "busy": [
    {
     "start": "2021-03-22T18:00:00Z",
     "end": "2021-03-22T19:00:00Z"
    },
    {
     "start": "2021-03-24T13:00:00Z",
     "end": "2021-03-24T16:00:00Z"
    }
   ]
  }
 }
}

知道如何访问“忙碌”数组中的信息......?

标签: node.jsarraysjsongoogle-apigoogle-api-nodejs-client

解决方案


通常,当您控制台记录嵌套对象(或您的情况下的响应主体)时,您会看到嵌套对象值[object object][Array]。您仍然可以解析对象以获取嵌套值,但如果您想在控制台日志中查看完整响应,您可以尝试console.log(JSON.stringify(res.data)).

解析响应并获取busy数组。

const busyArray = res.data.calendars.calendarid.busy;

推荐阅读