首页 > 解决方案 > 如何在另一个数组中的数组中获取值

问题描述

所以我尝试使用电子表格.values.get 从我的谷歌表中获取行,值的输出看起来像这样。

[
   'Name',
   'Date',
   'Rate',
   'Description',
   'Seasons'
],
[
   '2Name',
   '2Date',
   '2Rate',
   '2Description',
   '2Seasons'
],

我认为它的数组在数组中,我在编码方面不太好,我想将名称、日期、速率、描述和季节放入变量中,通过 discord.js 将其发布为嵌入并重复直到数组结束

这是整个代码:

const {google} = require('googleapis')
        const auth = new google.auth.GoogleAuth({
        keyFile: 'keys.json',
        scopes: 'https://www.googleapis.com/auth/spreadsheets',
        });

        GetValues();

        async function GetValues() {
          const googleClient = await auth.getClient();
          const googleSheets = google.sheets({version: 'v4', auth: googleClient});
          const spreadsheetId = 'IDHere';

          try {
            const response = (await googleSheets.spreadsheets.values.get({
              auth,
              spreadsheetId,
              range: 'A2:E',
              valueRenderOption: 'FORMATTED_VALUE',
              dateTimeRenderOption: 'SERIAL_NUMBER'
            })).data;
            console.log(response.values);
            //return(JSON.stringify(response, null, 2));
          } catch (err) {
            console.error(err);
          }
        };

如果您需要更多信息,请在评论中询问,谢谢

标签: node.jsarraysgoogle-sheetsdiscord.js

解决方案


好吧,通常您可以像往常一样访问数组中的数组。

这意味着data[0]将是外部数组中的第一个条目。您可以将其保存在一个值中,也可以只遍历外部数组的每个元素,这取决于您。一旦你有了内部,你几乎可以做同样的事情。

您还可以做的是data[0][0]外部数组中第一个元素的第一个值。

因此,使用您的示例数据:

const data = [
[
   'Name',
   'Date',
   'Rate',
   'Description',
   'Seasons'
],
[
   '2Name',
   '2Date',
   '2Rate',
   '2Description',
   '2Seasons'
]
];

const firstElement = data[0];将返回

[
   'Name',
   'Date',
   'Rate',
   'Description',
   'Seasons'
]

然后您可以使用相同的方法再次拆分。

另一方面data[0][0]会回归'Name'


推荐阅读