I'm trying to build a function that will extract the values from an object and creates an array of strings.
In the snippet below, you can see an example of what I did until now but that is not fully correct to my requirements.
Let's say I have data as in the example
const data = {
age: {
min: '17',
max: '66'
},
gender: ['male', 'female'],
rosacea: 'true',
rosacea_papulo_pustulosa: 'true',
severe_rosacea: 'true',
nurse_contact: 'true',
};
Right now I'm getting an array of strings for every single value in fact the result if you run it is
[
"17",
"66",
"male",
"female",
"true",
"true",
"true",
"true"
]
But what I need is the following array based if we have or not a nested object inside the data
[
* 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 is ok as no nested objects
"true",
"true",
"true",
"true"
]
The above result is what I'm searching
Another example as this below data
{disease":{"valid":["MDD","PTSD"],"invalid":["None"]}}
// result expected
[
"MDD - PTSD",
"None"
]
My issue at the moment is how to get into the expected results plus needs to be a - between the aggregated results.
We can also have a situation where data looks like this
{ageGroup: ["1","2","3", ..., "n"]}
// result expected
[
"1 - 2 - 3 ... etc ..."
]
The snippets abut my first 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
The nested objects will never go more deeply as per following example
age: {
group1: {
min: '1',
max: '6'
}
group2: {
min: '7',
max: '10'
}
},
Expected result as
[
'1 - 6',
'7 - 10'
]