I am currently delving into the realm of JavaScript and my instructor has given me an exercise to create a function that will output an array containing all the names from the nested object below:
{
name: 'grandma',
daughter: {
name: 'mother',
daughter: {
name: 'daughter',
daughter: {
name: 'granddaughter'
}
}
}
}
My predicament is akin to a query posted on Stack Overflow, but the provided solution does not quite fit my scenario as my object structure lacks arrays. The code snippet I have managed to put together thus far looks like this:
function convertToArray(obj) {
const result = [];
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result.push(convertToArray(value));
}
else {
result.push(value);
}
}
return result;
}
function extractNames(target) {
return convertToArray(target);
}
The output currently reads:
[ 'grandma', [ 'mother', [ 'daughter', [Array] ] ] ]
However, my instructor's expectations are aligned with:
['grandma', 'mother', 'daughter', 'granddaughter']