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

如何从patient.entries提取扁平诊断码数组,避免嵌套数组?

问题描述

我需要获取形如['Z57.1', 'Z74.3', 'M51.2']的诊断码数组,但通过map遍历patient.entries中的诊断码时,控制台返回[Array(3)](实际是二维数组[['Z57.1', 'Z74.3', 'M51.2']]),无法直接访问单个诊断码,请问如何修改遍历逻辑得到目标一维数组?

相关代码

const patient =  {
          id: 'd2773598-f723-11e9-8f0b-362b9e155667',
          name: 'Martin Riggs',
          dateOfBirth: '1979-01-30',
          ssn: '300179-777A',
          gender: Gender.male,
          occupation: 'Cop',
          entries: [
            {
              id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',
              date: '2019-08-05',
              type: 'OccupationalHealthcare',
              specialist: 'MD House',
              employerName: 'HyPD',
              diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],
              description:
                'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',
              sickLeave: {
                startDate: '2019-08-05',
                endDate: '2019-08-28',
              },
            },
          ],
        };
const codes = patient?.entries.map(c => c.diagnosisCodes);

当前返回结果

[Array(3)]
0: (3) ['Z57.1', 'Z74.3', 'M51.2']
length: 1
[[Prototype]]: Array(0)

解决方案

场景1:仅需提取第一个条目的诊断码

如果patient.entries中只会有一个需要处理的条目,直接通过索引获取即可:

const codes = patient?.entries[0]?.diagnosisCodes || [];

场景2:合并所有条目的诊断码到一维数组

如果patient.entries可能包含多个条目,每个都有diagnosisCodes数组,需要将所有诊断码合并成一个一维数组,可采用以下两种方式:

  • 使用flatMap(一步完成映射+扁平化,推荐):
const codes = patient?.entries.flatMap(entry => entry.diagnosisCodes) || [];
  • 先map再flat:
const codes = patient?.entries.map(entry => entry.diagnosisCodes).flat() || [];

原因说明

原代码中map会将每个条目的diagnosisCodes数组作为新数组的元素,最终得到二维数组。控制台显示的[Array(3)]是二维数组的简写形式,而非目标一维数组。上述方案通过直接取值或扁平化处理,将二维数组转换为一维数组,即可直接访问单个诊断码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:55:16