在 google 应用程序脚本中的 json 数组中创建动态键值

Creating dynamic keys values in json array in google apps script

我有这个数据工作簿 - dataset

现在,实际数据集可能有同一家公司的副本,我的最终目标是创建活动时间表,但这是另一个问题。

我在这里试图完成的是将此处以联系人为中心的数据(意味着每一行代表一个新联系人,而不是一家新公司)转换为以公司为中心的 JSON 数组。

这在下面的代码中表示

var companies = {
  'names':[]
};
function organiseLeads() {
  
  const leads = leadSheet.getDataRange().getValues();
    leads.splice(0,1);

  try {
    for (var i in leads) {
      var data = leads[i];
      var companyName = data[3];

      var exists = companies.names.some(function (company) {
        return company === companyName;
      });
Logger.log(exists);
      if (exists == false) {
        companies.names[companyName] = {
          'region': data[4],
          'type': data[5],
          'createDate': data[9],
          'ids': {
            'opportunityId': data[8],
            'accountId': data[7],
            'leadId': data[0]
          },
          'activities': [{
            'type': 'Lead Created',
            'date': data[9],
            'detail': data[2]
          }]
        }
      } else if (exists == true && data[9].valueOf() < companies[companyName].createDate) {
        companies.names[companyName].createDate = data[9];
        companies.names[companyName].activities.push({ 'type': 'Lead Created', 'date': data[9], 'detail': data[2] });
      } else if (exists == true && data[9].valueOf() > companies[companyName].createDate) {
        companies.names[companyName].activities.push({ 'type': 'Lead Created', 'date': data[9], 'detail': data[2] });
      }
    }
  } catch(e) {
    Logger.log(e);
    Logger.log(exists);
     Logger.log(data);
      Logger.log(companyName);
       Logger.log(companies.names);
  }
}

在此上下文中,leadSheet 指的是此处提到的数据集。它在其他地方的 Google 脚本中定义。

我也尝试过使用 companies.names.push([companyName = {}])(其中包含所有其他数据),但没有任何反应。

应该发生的是它检查公司是否已经存在于这个数组中。如果没有,它将创建为多维数组,使用公司名称作为主键,然后将详细信息作为嵌套键值对。

如果公司已经存在,它只是对该公司记录进行一些小的更改,然后 returns 整个 json 数组。

然而,发生的一切都不算什么。它根本不在 JSON 数组中设置任何内容。当我试图展平公司数组时,我得到错误 companies.some is not a function 和 exists 变量,它检查公司是否已经存在,总是returns 错误。

如何确保数据被正确地推入 JSON 数组?请记住,公司名称的密钥是动态生成的,而不是静态密钥。

我想保留上面代码中描述的 JSON 结构。

以公司为中心JSON

function companyCentricJson() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const [hA,...vs]= sh.getDataRange().getValues();
  const json = vs.reduce((a,[id,name,eml,co,reg,type,indus,acct,oppo,date],i) => {
    if(!a.obj.hasOwnProperty(co)) {
      a.obj[co] = [];
      a.obj[co].push(hA)
      a.obj[co].push([id,name,eml,co,reg,type,indus,acct,oppo,date]);
      a.obj.pA.push(co);
    } else {
      a.obj[co].push([id,name,eml,co,reg,type,indus,acct,oppo,date])
    }
    return a;
  },{obj:{pA:[]},json:function(){return JSON.stringify(this.obj)}}).json();
  Logger.log(json);
  return json;
}

数据Sheet:

Id Name Email Company Region Type Industry Account Id Opportunity Id Create Date
123446 Jon L Jon L@Company 1.com Company 1 None Enterprise 9078900.00% 44567800.00% 01-03-2020
123468 Frank F Frank F@Company 2.com Company 2 None Mobile Operator Telecommunications 9076500.00% 77654400.00% 01-03-2020
123490 Alex Y Alex Y@Company 3.com Company 3 EMEA 9074100.00% 110741000.00% 01-03-2020
123512 Ilya A Ilya A@Company 4.com Company 4 None 9071700.00% 143827600.00% 01-03-2020
123534 Mike M Mike M@Company 5.com Company 5 None 9069300.00% 176914200.00% 01-03-2020
123556 Narimon O Narimon O@Company 6.com Company 6 None Service Provider 9066900.00% 210000800.00% 01-03-2020
123578 Sagar S Sagar S@Company 7.com Company 7 None 9064500.00% 243087400.00% 02-03-2020
123600 John C John C@Company 8.com Company 8 None 9062100.00% 276174000.00% 02-03-2020
123622 Pete r Pete r@Company 9.com Company 9 None 9059700.00% 309260600.00% 02-03-2020
123644 Ivelin I Ivelin I@Company 10.com Company 10 None 9057300.00% 342347200.00% 02-03-2020
123666 Reginald R Reginald R@Company 11.com Company 11 None Enterprise 9054900.00% 375433800.00% 02-03-2020
123688 Yossi R Yossi R@Company 12.com Company 12 None Enterprise 9052500.00% 408520400.00% 02-03-2020
123710 Joey K Joey K@Company 13.com Company 13 None Service Provider 9050100.00% 441607000.00% 02-03-2020

JSON:

{"pA":["Company 1","Company 2","Company 3","Company 4","Company 5","Company 6","Company 7","Company 8","Company 9","Company 10","Company 11","Company 12","Company 13"],"Company 1":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123446,"Jon L","Jon L@Company 1.com","Company 1","None","Enterprise","",90789,445678,"2020-03-01T07:00:00.000Z"]],"Company 2":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123468,"Frank F","Frank F@Company 2.com","Company 2","None","Mobile Operator","Telecommunications",90765,776544,"2020-03-01T07:00:00.000Z"]],"Company 3":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123490,"Alex Y","Alex Y@Company 3.com","Company 3","EMEA","","",90741,1107410,"2020-03-01T07:00:00.000Z"]],"Company 4":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123512,"Ilya A","Ilya A@Company 4.com","Company 4","None","","",90717,1438276,"2020-03-01T07:00:00.000Z"]],"Company 5":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123534,"Mike M","Mike M@Company 5.com","Company 5","None","","",90693,1769142,"2020-03-01T07:00:00.000Z"]],"Company 6":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123556,"Narimon O","Narimon O@Company 6.com","Company 6","None","Service Provider","",90669,2100008,"2020-03-01T07:00:00.000Z"]],"Company 7":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123578,"Sagar S","Sagar S@Company 7.com","Company 7","None","","",90645,2430874,"2020-03-02T07:00:00.000Z"]],"Company 8":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123600,"John C","John C@Company 8.com","Company 8","None","","",90621,2761740,"2020-03-02T07:00:00.000Z"]],"Company 9":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123622,"Pete r","Pete r@Company 9.com","Company 9","None","","",90597,3092606,"2020-03-02T07:00:00.000Z"]],"Company 10":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123644,"Ivelin I","Ivelin I@Company 10.com","Company 10","None","","",90573,3423472,"2020-03-02T07:00:00.000Z"]],"Company 11":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123666,"Reginald R","Reginald R@Company 11.com","Company 11","None","Enterprise","",90549,3754338,"2020-03-02T07:00:00.000Z"]],"Company 12":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123688,"Yossi R","Yossi R@Company 12.com","Company 12","None","Enterprise","",90525,4085204,"2020-03-02T07:00:00.000Z"]],"Company 13":[["Id","Name","Email","Company","Region","Type","Industry","Account Id","Opportunity Id","Create Date"],[123710,"Joey K","Joey K@Company 13.com","Company 13","None","Service Provider","",90501,4416070,"2020-03-02T07:00:00.000Z"]]}

读取数据的对话框

GS:

function getCompanyInfo(name="Company 1") {
  const vs = JSON.parse(companyCentricJSON())[name];
  //Logger.log(JSON.stringify(vs));
  return vs.reduce((a,c,i) => {
    if(i == 0) {
      a.hl += '<tr>'
      c.forEach(e => a.hl += '<th>' + e + '</th>');
      a.hl += '</tr>'
    } else {
      a.hl += '<tr>'
      c.forEach(e => a.hl += '<td>' + e + '</td>');
      a.hl += '</tr>'
    }
    return a;
  },{hl:"<style>th,td{border:1px solid black;}</style><table>",getHtml:function(){return this.hl + '</table>'}}).getHtml();
}

function getMySelects() {
  return JSON.parse(companyCentricJSON()).pA
}

function launchCompanyCentricDialog() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile("ah4").setWidth(1200),"Company Centric Info Dialog")
}

html: ("ah4.html"):

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <select id="sel1" onChange="displayData();" placeholder="Select Company"></select>
    <div id="data"></div>
    <div id="msg"></div>

    <script>
      window.onload = function() {
        google.script.run
        .withSuccessHandler(function (obj){
          updateSelect(obj)
        })
        .getMySelects()
      }
     function updateSelect(vA,id){
      var id=id || 'sel1';
      var select = document.getElementById(id);
      select.options.length = 0; 
      vA.unshift("");
      for(var i=1;i<vA.length;i++){
        select.options[i] = new Option(vA[i],vA[i]);
      }
    }
    function displayData() {
      let val = document.getElementById("sel1").value;
      google.script.run
      .withSuccessHandler(function (hl) {
        document.getElementById("data").innerHTML = hl;
      })
      .getCompanyInfo(val);
    }
    </script>
  </body>
</html>

对话演示:

我最终让它与这个一起工作

function organiseLeads() {

  const [headers, ...leads] = leadSheet.getDataRange().getValues();

  try {
    for (var i in leads) {
      var [leadId, name, email, companyName, region, type, industry, accountId, oppId, createdDate] = leads[i];
      var date = Utilities.formatDate(createdDate,"GMT","dd-MM-yyyy");

      if (!companies.names.hasOwnProperty(companyName)) {
        companies.names[companyName] = {};
        companies[companyName] = {
          'region': region,
          'type': type,
          'createDate': date,
          'ids': {
            'opportunityId': oppId,
            'accountId': accountId,
            'leadId': leadId
          },
          'activities': [{
            'type': 'Lead Created',
            'date': date,
            'detail': email
          }]
        }
      } else if (companies.names.hasOwnProperty(companyName) && date.valueOf() < companies.names[companyName].createDate) {
        companies.names[companyName].createDate = date;
        companies.names[companyName].activities.push({ 'type': 'Lead Created', 'date': date, 'detail': email });
      } else if (companies.names.hasOwnProperty(companyName) && createdDate.valueOf() > companies.names[companyName].createDate) {
        companies.names[companyName].activities.push({ 'type': 'Lead Created', 'date': date, 'detail': email });
      }
    }
    Logger.log(companies)
    return companies;
  } catch (e) {
    Logger.log(e);
    Logger.log(companies.hasOwnProperty(companyName));
    Logger.log("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s",leadId, name, email, companyName, region, type, industry, accountId, oppId, date);
    Logger.log(companyName);
    Logger.log(companies);
  }

我将 companies.some() 换成了 .hasOwnProperty(),因为它的检查效果更好,速度更快。在我首先添加嵌套键值对之前,我还必须声明公司。最后,我添加了一个名为 'names' 的嵌套元素。我不确定我是否需要这个。

我认为@Cooper 有一个很好的答案,可以更容易地查看压缩代码,它只是没有解决我的特定用例问题。我会尝试根据我的需要更新他的解决方案。