I'm currently working on a function to extract values from an object and generate an array of strings.
In the snippet below, I have provided an example of my progress so far, but it does not completely meet my requirements.
For instance, consider the data in this example:
const data = {
age: {
min: '17',
max: '66'
},
gender: ['male', 'female'],
rosacea: 'true',
rosacea_papulo_pustulosa: 'true',
severe_rosacea: 'true',
nurse_contact: 'true',
};
Currently, the output is an array of individual strings for each value, as shown:
[
"17",
"66",
"male",
"female",
"true",
"true",
"true",
"true"
]
However, what I need is an array that considers nested objects within the data. The desired output should be:
[
* This is the result of age min: '17' and max: '66'
"17 - 66",
* This is the result of gender male and female
"male - female",
* The rest remains the same without nested objects
"true",
"true",
"true",
"true"
]
The above output is what I am aiming for.
Here is another example with the following data:
{disease":{"valid":["MDD","PTSD"],"invalid":["None"]}}
// expected result
[
"MDD - PTSD",
"None"
]
My challenge at the moment is achieving the expected results while adding a -
between the aggregated values.
We might encounter scenarios like the one shown below:
{ageGroup: ["1","2","3", ..., "n"]}
// expected result
[
"1 - 2 - 3 ... etc ..."
]
The following code shows my initial attempt:
const data = {
age: {
min: '17',
max: '66'
},
gender: ['male', 'female'],
rosacea: 'true',
rosacea_papulo_pustulosa: 'true',
severe_rosacea: 'true',
nurse_contact: 'true',
};
const getValues = (data, values = []) => {
if (typeof data !== 'object') {
return [...values, data];
}
return Object.values(data).flatMap((v) => getValues(v, values));
};
console.log(getValues(data))
Update
Nested objects will not go deeper than the following example:
age: {
group1: {
min: '1',
max: '6'
}
group2: {
min: '7',
max: '10'
}
},
Expected result:
[
'1 - 6',
'7 - 10'
]