Home > Back-end >  Creating dynamic keys values in json array in google apps script
Creating dynamic keys values in json array in google apps script

Time:04-26

I have this workbook of data - enter image description here

CodePudding user response:

I ended up making it work with this

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

I switched out the companies.some() for .hasOwnProperty(), as it is a better check and faster. I also had to declare the company before I added in the nested key value pair first. And lastly I added a nested element called 'names'. I'm not sure I need this.

I think @Cooper has a great answer that would make it easier to look at condense the code, it just didn't solve my particular use case problem. I will try to update his solution to my needs.

  • Related