跳转到主要内容
当在代码操作中与数组一起工作时,您可能会遇到两个共同的挑战:
  1. 作为字符串传递的数组 - 来自外部系统或前几步的数据作为字符串而不是实际数组
  2. 不能选择单个项目 — 您只能选择整个数组,而不是其中的特定字段
两者都可以用代码节点解决。

从字符串解析数组

数组通常是作为字符串或 JSON 而不是本机数组在工作流步骤之间传递的。 这种情况发生在:
  • 通过 HTTP 请求从外部 API 接收数据
  • 正在处理 webhook payload
  • 工作流步骤之间传输数据
Solution:在代码开始时添加此模式:
export const main = async (params: {
  users: any;
}): Promise<object> => {
  const { users } = params;

  // Handle input that may come as a string or an array
  const usersFormatted = typeof users === "string" ? JSON.parse(users) : users;

  // Now you can safely work with usersFormatted as an array
  return {
    users: usersFormatted.map((user) => ({
      ...user,
      activityStatus: String(user.activityStatus).toUpperCase(),
    })),
  };
};
键行 typeof users === "string" ? JSONparse(users) : users检查输入是否是字符串, 如果需要解析它, 或者如果它已经是一个数组直接使用它。

从数组中提取个别字段

Web 钩子可能返回一个数组,如’答案: […]’, 但在随后的工作流步骤中,您只能选择 整个数组 ——而不是其中的个别项目。 Solution: 添加代码节点来提取特定字段并将其作为结构化对象返回:
export const main = async (params: {
  answers: any;
}): Promise<object> => {
  const { answers } = params;

  // Handle input that may come as a string or an array
  const answersFormatted = typeof answers === "string"
    ? JSON.parse(answers)
    : answers;

  // Extract specific fields from the array
  const firstname = answersFormatted[0]?.text || "";
  const name = answersFormatted[1]?.text || "";

  return {
    answer: {
      firstname,
      name
    }
  };
};
代码节点返回结构化对象而不是数组。 在随后的步骤中,您现在可以从变量选择器中选择单个字段,例如answer.firstnameanswer.name
想要遍历数组而不是提取字段? 当一个 Code 或 Logic Function 步骤返回顶层数组时,你可以将其直接传入 Iterator:在 Iterator 的输入中选择该步骤的 Whole list 选项,然后在循环内部使用 {{iterator.currentItem}} 引用每个元素。 在那种情况下,你不需要将数组重构为对象。
点击代码编辑器右上角的方形图标在全屏显示它——因为默认编辑器宽度是有限的,所以它是有用的。