【问题标题】:Calling Json Objects With Parameters Passed to Function使用传递给函数的参数调用 Json 对象
【发布时间】:2018-10-27 16:13:01
【问题描述】:

我遇到了一个有趣的困境——我想编写一个函数,给定几个参数,它将根据另一个值在 JSON 响应中返回一个对象/参数。

片段 1 展示了一种我可以通过简单的大小写检查来做到这一点的方法:

function callf() {
  return f("name", "project_id", "sampleName");
}

function f(Where, Return, Is) {
  var options = {
    "option1": "asdf",
    "option2": "asdf"
  }
  var url = "..."
  var response = UrlFetchApp.fetch(url, options);
  var jsonResponse = JSON.parse(response.getContentText());
  for (i in jsonResponse) {
    if (Where == "object1") {
      //Instead of dynamically calling the object, use case testing to call the desired object.
      if (jsonResponse[i].object1 == Is) {
        if (Return = "returnValue1") {
          return jsonResponse[i].returnValue1;
        } else if (Return = "returnValue2") {
          return jsonResponse[i].returnValue2;
        }
      }
    } else if (Where == "object2") {
      if (jsonResponse[i].object2 == Is) {
        if (Return = "returnValue1") {
          return jsonResponse[i].returnValue1;
        } else if (Return = "returnValue2") {
          return jsonResponse[i].returnValue2;
        }
      }

    }
  }

但是,按照上述方式,我必须考虑 json 响应包含的每个可能的对象,这将是一件痛苦的事情。我想找到一个替代方法,我可以简单地传递一个字符串,该字符串表示我想从下面的 sn-p 之类的函数返回的对象:

function callf(){
  return f("name","project_id","sampleName");
}

function f(Where,Return,Is){
  var options = {
    "option1":"asdf",
    "option2":"asdf"
  }
  var url = "..."
  var response = UrlFetchApp.fetch(url,options);
  var jsonResponse = JSON.parse(response.getContentText());
  for(i in jsonResponse){
    if(jsonResponse[i].(Where)==Is){
      return jsonResponse[i].(Return);
    }
  }
}

我该如何做到这一点?

【问题讨论】:

  • 如果解决了您的问题,请标记为已回答。最好的。

标签: javascript arrays json google-apps-script logic


【解决方案1】:

就像您使用方括号以 i 变量作为键访问 json 一样,

for(var i in jsonResponse){
  if(jsonResponse[i][Where]==Is){
    return jsonResponse[i][Return];
  }
}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
相关资源
最近更新 更多