Skip to content

Instantly share code, notes, and snippets.

@niquola
Created November 20, 2024 16:40
Show Gist options
  • Save niquola/26875e7cedebb62cd7f880d8e42c7934 to your computer and use it in GitHub Desktop.
Save niquola/26875e7cedebb62cd7f880d8e42c7934 to your computer and use it in GitHub Desktop.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment