I've got an object that looks like this:
{
parent: {
child1: {
key: 'value'
},
child2: {
key: 'value'
},
child3: {
key: 'value'
}
}
}
I need to transform it to an object that looks like this:
{
title: 'parent',
children: [{
title: 'child1',
children: [{
title: 'key',
value: 'value'
}]
}, {
title: 'child2',
children: [{
title: 'key',
value: 'value'
}]
}, {
title: 'child3',
children: [{
title: 'key',
value: 'value'
}]
}]
}
I ended up with a following function:
function transform(obj) {
const result = {
title: '',
children: []
};
for (let key in obj) {
let child = obj[key];
result.title = key;
if (typeof(child) === 'string') {
delete result.children;
result.value = child;
} else {
result.children.push(transform(child));
}
}
return result;
}
But when I run it, it returns me the following output, which is wrong:
{
title: 'parent',
children: [{
title: 'child3',
children: [
{ title: 'key', value: 'value' },
{ title: 'key', value: 'value' },
{ title: 'key', value: 'value' }
]
}]
}
Could anyone point out what exactly is my mistake in the function, please?