Suggest an algorithm to turn linear structures like this
[ {path: 'a', value: 'k'}, {path: 'b', value: 'l'}, {path: 'b.c', value: 'm'}, {path: 'd', value: 'n')]
list of path and value objects into a nested data-structure like this:
{ elements: { a: {value: 'k'}, b: {value: 'l', elements: {c: {value: 'm'}}, d: {value: 'n'}}
I.e turn paths into nested object!
Now let's complicate a little bit by introducing compartments. The initial list consists of objects with path, value and optional "component". Components create subtrees in the resulting structure. Here is an example of input and output:
// input
const list = [
{ path: 'a', value: 'k' },
{ path: 'b', value: 'l' },
{ path: 'b', component: 'x' },
{ path: 'b.c', value: 'm' },
{ path: 'b.d', value: 'n' }
{ path: 'b', component: 'y' },
{ path: 'b.c', value: 'r' },
{ path: 'b.d', value: 's' },
{path: 'e', value: 'q'}
];
//output
{
elements: {
a: { value: 'k' },
b: {
value: 'l',
components: {
x: {elements: {c: {value: 'n'}, d: {value: 'm'}},
y: {elements: {c: {value: 'r'}, d: {value: 's'}},
}
},
e: { value: 'q'}
}
}
Provide algorithm to convert from list to nested data structure