调用深度嵌套数组

时间:2020-06-23 04:18:33

标签: javascript google-apps-script

我有一个预期的JSON负载,该负载在嵌套数组/对象中非常深。当我根据假定的结构分配变量时

{
  id: value1,
  name: value2,
  data: {
    status: complete,
    date: 2020 - 06 - 20,
    notes: {
      field1: "user notes",
      field2: "more user notes"
    }
  }
}

在我的代码中,我将这样拨打电话:

var usernote = payload.data.notes.field1 || "No Notes"

但是,用户可能没有提出任何注释,因此注释对象将返回未定义状态。无论如何,是否没有执行一系列级联的默认检查?我的一些电话看起来像这样:

priorityvar = payload.data.form_values["b691"][index]["form_values"]["d54d"]["choice_values"][0]

任何帮助将不胜感激,我在搜索中找不到相似的答案(但这里也很新)。另外,我正在使用Google脚本,因此无法使用任何ES6内容。

2 个答案:

答案 0 :(得分:2)

我想避免重复检查的唯一方法(因为您使用的是Google脚本,并且“ 不能使用任何ES6内容”)是使用try catch方法。

这将为您验证整个表达式,因此您不必担心对象中的各个键验证:

var usernote;

try {
  usernote = payload.data.notes.field1;
} catch (error) {
  usernote = "No Notes";
}

面向可以使用较新技术的人

新的ECMA脚本2020刚刚于上周发布,现在 optional chaining 是官方的事情。

它使您可以执行以下操作,而不必担心这些值中的任何一个是否为undefined

var usernote = payload?.data?.notes?.field1 || "No Notes"

从文档中:

可选的链接运算符允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效

答案 1 :(得分:1)

您可以使用lodash的ReferenceError: client is not defined at Object.execute (D:\drpa-bot\big bin\commands\game-start.js:5:3) at Client.<anonymous> (D:\drpa-bot\big bin\index.js:28:31) at Client.emit (events.js:315:20) at MessageCreateHandler.handle (D:\drpa-bot\big bin\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34) at WebSocketPacketManager.handle (D:\drpa-bot\big bin\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65) at WebSocketConnection.onPacket (D:\drpa-bot\big bin\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35) at WebSocketConnection.onMessage (D:\drpa-bot\big bin\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17) at WebSocket.onMessage (D:\drpa-bot\big bin\node_modules\ws\lib\event-target.js:120:16) at WebSocket.emit (events.js:315:20) at Receiver.receiverOnMessage (D:\drpa-bot\big bin\node_modules\ws\lib\websocket.js:789:20) Called command: <@253506821438832640>, 函数。它将尝试访问与给定路径匹配的对象内的值。这里是the offical documentation的一些示例。

_.get(obj, path, defaultValue)

如果您不能导入lodash,请尝试实现一个。

P.S。 我粗心地发布了链接到中文文档的链接。我已经更新了它,现在它链接到英语版本。