My grasp of JS is still in its early stages, so understanding how the stack and recursion function can be challenging for me at this point. The task at hand involves displaying an array of object keys, including the parent object name if the object is nested.
For instance, consider the following object:
{
a: {
b: 2,
q: [0, 3, 4],
},
x: true,
d: { f: null,
c: 'something'
}
}
The goal is to generate an array of keys as follows:
[
'a.b', 'a.q',
'a.q.0', 'a.q.1',
'a.q.2', 'x',
'd.f', 'd.c'
]
It's evident that nested keys should have a fully qualified name, separated by a dot from the parent name.
I managed to solve this issue but with extensive conditional statements and loops, tailored specifically for this object. Any added nesting would make the function non-functional.
function getKeysArray(obj) {
let array = [];
for (const key of Object.keys(obj)) {
if (typeof obj[key] !== 'object') {
array.push(key);
}
let internObj = obj[key];
if (typeof internObj === 'object') {
for (const innerKey of Object.keys(internObj)) {
array.push(`${key}.${innerKey}`);
let mostInnerKey = internObj[innerKey];
if (typeof mostInnerKey === 'object' && internObj[innerKey] !== null) {
for (const index of Object.keys(mostInnerKey)) {
array.push(`${key}.${innerKey}.${index}`)
}
}
}
}
}
return array;
}
While I've solved a similar problem involving values instead of keys using recursion, doing the same for this challenge seems perplexing to me.
Although I've come across solutions on StackOverflow for similar problems, none required displaying full key names in this manner.