In my app, I need an array of diagnosis codes in the form of ['Z57.1', 'Z74.3', 'M51.2'] so I can have access to each of them.
However, when mapping through diagnosis codes, I get [Array(3)] in the console instead of ['Z57.1', 'Z74.3', 'M51.2'], meaning I can't get access to the codes.
How do you map through patient.entries to return ['Z57.1', 'Z74.3', 'M51.2'] in the console instead of [Array(3)]?
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);
const codes returns:
[Array(3)]
0
:
(3) ['Z57.1', 'Z74.3', 'M51.2']
length
:
1
[[Prototype]]
:
Array(0)
CodePudding user response:
You could use Array.prototype.flatMap
.
It works like map, but flattens nested arrays into a single monolithic array.
Your main issue is that you have n-number of entries with m-number of diagnosis codes. Your resulting array of codes will be 2-dimensional. Flattening the matrix will result in a linear array.
const main = () => {
const codes = patient.entries.flatMap(c => c.diagnosisCodes);
console.log(codes);
};
const Gender = { male: 'Male', female: 'Female', other: 'Other' };
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',
}
}]
};
main();
CodePudding user response:
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.reduce((t, v) => [...t, ...v.diagnosisCodes], []);
console.log(codes);