JS - 对象到数据到Google表格批量更新

时间:2017-03-09 21:38:14

标签: javascript arrays google-sheets javascript-objects google-sheets-api

我已经在这里工作了几天,似乎正在取得进展,但我无法弄清楚错误。目标:从本地服务器查询,将结果存储到可以发送到"值的数组中。谷歌工作表batchUpdate的属性。

我对整个异步事情感到很难过,但我觉得我现在已经掌握了Promise并且它的工作有点......

到目前为止,我的代码看起来像这样:

function begin(auth) {

var theArray = [];

let getResults = (passedQuery) => {
    return new Promise((resolve, reject) => {
        client.connect();
        var sql = client.query(passedQuery);

        sql.on('row', (row, result) => {
            result.addRow(row);
        });

        sql.on('end', (result) => {
            resolve(result.rows); // Array.from(result.rows)??
            client.end();
        });

    });
}

// may not even need this...    
let convertArray = (sqlObj) => {
    return new Promise((resolve, reject) => {

        theArray = Object.keys(sqlObj).map((k) => {
            return [sqlObj[k]];
        });

        console.log(theArray);

        // sqlObj.forEach((element) => {
        //     theArray.push(element);
        // })

        // theArray = sqlObj.reduce((result, item) => {
        //     var key = Object.keys(item)[0]; // first property
        //     result[key] = item[key];
        //     return result;
        // }, []);

        // console.log(theArray);            
        resolve(theArray);

        // while (sqlObj.length) {
        //     theArray.push(sqlObj.splice(0, sqlObj.length));
        //     console.log(sqlObj.length);
        // }            
        // console.log('convertArray should be done and now includes: \n'+JSON.stringify(theArray));

        // resolve(theArray);
    });
}

let updateSheets = (myArray) => {
    return new Promise((resolve, reject) => {

        var update_range = "Sheet1!A:Z";
        var valueInputOption = "RAW";
        var sheets = google.sheets('v4');

        var options = {
            auth: auth,
            spreadsheetId: spreadsheetId,
            resource: {
                valueInputOption: valueInputOption,
                data: [
                    {
                        range: update_range,
                        majorDimension: "COLUMNS",
                        // values: [[JSON.stringify(myArray,null,' ')]] // stringify and it works...in 1 cell...
                        values: myArray // this should be values only! NO KEYS / COLUMN HEADERS
                    }
                ]
            }
        }

        sheets.spreadsheets.values.batchUpdate(options, (err, res) => {
            if (err) {
                reject(err);
            } else {
                console.log(res);
                resolve(res);
            }
        });
    });
}

getResults('SELECT item_number,item_descrip1 FROM item WHERE item_number LIKE \'23-%\' LIMIT 10')
    .then((sqlObj) => {
        console.log('Converting object to array...hopefully...');
        return convertArray(sqlObj);
    })
    .then((convertedObj) => {
        console.log('Updating sheets...');


           return updateSheets(convertedObj);
        })
        .catch((error) => {
            console.log('Something went wrong...\n%s', error);
        })
}

您可以通过我的评论看到我一直在尝试各种方法让对象进入[x] D数组(基于查询返回的列数)

实际上,我的结果......

    Info: Start process (1:30:25 PM)
Converting object to array...hopefully...
[ [ anonymous {
      item_number: '23-1240',
      item_descrip1: 'Dev1 TX SDI with Lemo' } ],
  [ anonymous {
      item_number: '23-1241',
      item_descrip1: 'Dev1 RX SDI with Lemo' } ],
  [ anonymous { item_number: '23-0042-B', item_descrip1: 'Dev2 Assy' } ],
  [ anonymous { item_number: '23-0036-B', item_descrip1: 'Dev3 Assy' } ],
  [ anonymous { item_number: '23-0026-B', item_descrip1: 'Dev4 Ship Kit' } ],
  [ anonymous {
      item_number: '23-0055',
      item_descrip1: 'Dev5 TX SDI Unicast Assy' } ],
  [ anonymous { item_number: '23-0118', item_descrip1: 'Dev6 AB Mount' } ],
  [ anonymous { item_number: '23-0119', item_descrip1: 'Dev7 V Mount' } ],
  [ anonymous {
      item_number: '23-0203',
      item_descrip1: 'Dev8 RX HDMI' } ],
  [ anonymous {
      item_number: '23-0206',
      item_descrip1: 'Dev9 TX HDMI' } ] ]
Updating sheets...
Something went wrong...
Error: Invalid data[0]: Invalid values[0][0]: struct_value {
  fields {
    key: "item_number"
    value {
      string_value: "23-1240"
    }
  }
  fields {
    key: "item_descrip1"
    value {
      string_value: "Dev1 TX SDI with Lemo"
    }
  }
}

Info: End process (1:30:26 PM)

我非常有信心这些关键词' batchUpdate调用不理解数组中的数组,但我的尝试是删除它仍然给我类似的结果。

1 个答案:

答案 0 :(得分:0)

同事能够为我提供答案。我正在分享为我的后代制作此功能的结果。

    let convertArray = (sqlObj) => {
    return new Promise((resolve, reject) => {

        var result = [];

        if (sqlObj.length > 0) {
            var order = Object.keys(sqlObj[0]).map(function (k) {
                return k;
            });
            console.log(order);
            var result = [];
            for (var i = 0; i < sqlObj.length; ++i) {
                result.push(order.map(function (k) {
                    return sqlObj[i][k];
                }));
            }
        }
        console.log(result);

        resolve(result);
    });
}