简体   繁体   English

将数组作为 URL 参数 JavaScript/GAS 传递

[英]Passing arrays as URL parameter JavaScript/GAS

I have two functions.我有两个功能。

One queries for project id, project name, and project status and saves them up in an array.This works fine.一个查询项目 id、项目名称和项目状态并将它们保存在一个数组中。这很好用。

function get_All_Projects() {
    var options = {
        method: "get",
        headers: {
            Authorization: "Bearer " + tkft_token
        }
    };
    var url = tkft_url + endpoint + "auth=" + tkft_token + pages;
    var response = UrlFetchApp.fetch(url, options);
    var info = JSON.parse(response);
    var content = info.data;    
    var project_arr = [];
    var identity = {};  
    for (var i = 0; i < content.length; i++) {
        if (content.length > 0) {
            identity.Project_ID = content[i].id;
            identity.Project_Name = content[i].name;
            identity.Project_Start_Date = content[i].starts_at;
            identity.Project_End_Date = content[i].ends_at;
            identity.Project_Status = content[i].project_state; 
            project_arr.push(identity);
        }
    }
    //Logger.log(project_arr);
}

The second function is supposed to use the Id saved up in the project_arr so that I can get all users per project.第二个函数应该使用保存在 project_arr 中的 Id,以便我可以获取每个项目的所有用户。 The challenge is, I am having a hard time including one of the array objects in the URL for this function and also looping through every project id.挑战是,我很难在此函数的 URL 中包含数组对象之一,并且还要遍历每个项目 ID。 I keep running into Cannot read property 'length' of undefined error, Is there something I am missing?我一直遇到无法读取未定义错误的属性“长度”,我错过了什么吗?

function get_By_Users(project_arr) {
    var options = {
        method: 'get',
        headers: {
            Authorization: 'Bearer ' + tkft_token
        }
    };

    for (var i = 0; i<project_arr.length; i++) {  
        var url = tkft_url+ 'projects/'+ project_arr.Project_ID +'/users?auth='+ tkft_token + pages
        var response = UrlFetchApp.fetch(url,options); 
        var info= JSON.parse(response); 
        var content = info.data;
    }

    Logger.log(content);
}

I am surprised that this code works with no Promises or async, if it really does a URL fetch.我很惊讶这段代码在没有承诺或异步的情况下工作,如果它真的进行了 URL 获取。 Or is that a mock?还是那是个笑话?

Anyway, rather than a loop and Array.push, you can just use Array.map to do a data transform.无论如何,您可以使用 Array.map 进行数据转换,而不是循环和 Array.push。

Also, you can use a template string, rather than string concatenation.此外,您可以使用模板字符串,而不是字符串连接。

function get_All_Projects() {
    const options = {
        method: "get",
        headers: {
            Authorization: "Bearer " + tkft_token
        }
    };
    const url = `${tkft_url}${endpoint}auth=${tkft_token}${pages}`
    const response = UrlFetchApp.fetch(url, options);
    const info = JSON.parse(response);
    const content = info.data;    
    const project_arr = content.map(item => ({
        Project_ID: item.id;
        Project_Name: item.name;
        Project_Start_Date: item.starts_at;
        Project_End_Date: item.ends_at;
        Project_Status: item.project_state; 
    }))
    return project_arr
}

Then you need to call get_By_Users with the project_arr :然后你需要使用project_arr调用get_By_Users

const allProjects = get_All_Projects()
get_By_Users(allProjects)

This one flattens down even more with Array.map.这个使用 Array.map 更加扁平化。

async function get_By_Users(project_arr) {
    var options = {
        method: 'get',
        headers: {
            Authorization: 'Bearer ' + tkft_token
        }
    };

   const makeUrl = p => `${tkft_url}projects/${p.Project_ID}/users?auth=${tkft_token}${pages}`

  const safeJSONparse = item => {
    try {
      return JSON.parse(item)
    } catch (e) {
      return {data: undefined}
    }
  }

  const data = project_arr.map(p =>
     safeJSONparse(UrlFetchApp.fetch(makeUrl(p), options)).data))

    Logger.log(data);
}

You always need to try / catch with JSON.parse, because it throws if it can't parse the input.您总是需要使用 JSON.parse 来尝试/捕获,因为如果它无法解析输入,它就会抛出。 You then need to decide how your application will behave when this happens.然后,您需要决定您的应用程序在发生这种情况时的行为方式。 20% of coding is getting it to work. 20% 的编码让它发挥作用。 The other 80% is coding for what happens when it doesn't work.剩下的 80% 是编码它不起作用时会发生什么。

See this article for why to use Array.map, and this one for why to use const .请参阅这篇文章为什么要使用Array.map,和这一次为什么要使用const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM