You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JSONata遍历personalHistory生成并追加medicalCondition数组?

个人病史JSON转指定格式的实现方案

直接上JavaScript实现代码,涵盖所有需求场景:

function transformMedicalHistory(input) {
  // 先把病史字段和目标病症的对应关系理清楚
  const conditionMap = {
    hadmigraines: {
      type: "MIGRAINE",
      // 偏头痛的发作频率字段关联
      episodeField: "hadmigraines4InAMonth",
      count: 4,
      freq: "MONTHLY"
    },
    hadheartDisease: { type: "HEART_DISEASE" },
    hadhighCholesterol: { type: "HIGH_CHOLESTEROL" }
  };

  const medicalConditions = [];
  const history = input.personalHistory || {};

  // 遍历所有病史项,只挑值为true的处理
  for (const [key, isPositive] of Object.entries(history)) {
    if (!isPositive) continue;

    const config = conditionMap[key];
    if (!config) continue;

    const condition = { conditionType: config.type };
    // 如果是偏头痛且发作频率字段也为true,加上发作信息
    if (config.episodeField && history[config.episodeField]) {
      condition.numberEpisodesTotal = config.count;
      condition.frequency = config.freq;
    }

    // 防止偏头痛被重复添加(因为两个字段都是true)
    if (!medicalConditions.some(c => c.conditionType === config.type)) {
      medicalConditions.push(condition);
    }
  }

  // 拼出最终的输出结构
  return {
    oLifE: {
      party: [
        {
          person: { firstName: input.firstName || "" },
          risk: { medicalCondition: medicalConditions }
        }
      ]
    }
  };
}

// 测试有病症的情况
const testInput1 = {
  "firstName": "Jane",
  "personalHistory": {
    "hadmigraines": true,
    "hadmigraines4InAMonth": true,
    "hadheartDisease": true,
    "hadhighCholesterol": false
  }
};
console.log(JSON.stringify(transformMedicalHistory(testInput1), null, 2));

// 测试无病症的情况
const testInput2 = {
  "firstName": "John",
  "personalHistory": {
    "hadmigraines": false,
    "hadheartDisease": false,
    "hadhighCholesterol": false
  }
};
console.log(JSON.stringify(transformMedicalHistory(testInput2), null, 2));

逻辑说明

  1. 字段映射:用conditionMap把输入里的hadxxx字段和输出的病症类型、发作信息对应起来,方便后续统一处理。
  2. 筛选有效病症:遍历病史对象,只处理值为true的字段,直接过滤掉所有阴性记录。
  3. 特殊病症处理:针对偏头痛这种需要结合两个字段的情况,检查关联的发作频率字段是否为true,是的话就补上发作次数和频率,同时避免重复添加同一种病症。
  4. 无病症场景兼容:当所有病史都是阴性时,medicalCondition会自动变成空数组,完全符合输出结构要求。
  5. 容错处理:加了对输入字段缺失的判断,比如没有personalHistory或者firstName时,不会报错,而是生成合理的默认值。

无病症场景的输出示例

运行第二个测试用例,会得到以下输出:

{
  "oLifE": {
    "party": [
      {
        "person": {
          "firstName": "John"
        },
        "risk": {
          "medicalCondition": []
        }
      }
    ]
  }
}

内容的提问来源于stack exchange,提问作者kk29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:12:54