I'm doing a code where I have to traverse a nested object and return all the values in a single string. For example, if this is the input:
var obj = {
name: "root",
contents: [
{
name: "A",
contents: [
{
name: "fileA1",
contents: ["Hello!"]
}
]
},
{
name: "B",
contents: [
{
name: "dirB1",
contents: [
{
name: "fileB1.1",
contents: ["Hello!"]
}
]
}
]
}
]
};
The output should be:
root
A
fileA1
Hello!
B
dirB1
fileB1.1
Hello!
My code is:
function toArray(obj) {
var result = '';
for (const prop in obj) {
const value = obj[prop];
if (typeof value === 'object') {
result+=(toArray(value));
}
else {
result+=(value);
}
}
//console.log(result);
return result;
}
But when I run it, it returns the following string:
Hello!
fileA1undefined
undefined
Aundefined
Hello!
fileB1.1undefined
undefined
dirB1undefined
undefined
Bundefined
undefinedundefined
rootundefined
Why am I getting the "undefined" with the values and how can I fix this?