(Vue/Vanilla) Dynamically creating bracket-notation path through nested object array?

(Vue/Vanilla) Dynamically creating bracket-notation path through nested object array?

erk

New member
Local time
13:43
Joined
May 25, 2020
Messages
1

Hi, I have to navigate data with the following sample structure, which will be generated and passed from the backend:

JavaScript:
const data = [
  {
    uid: 'aa',
    type: 'branch',
    branch: [
      { uid: 'ff', type: 'text' },
      { uid: 'hh', type: 'text' },
      {
        uid: 'dd',
        type: 'branch',
        branch: [
          { uid: 'gg', type: 'text' },
          { uid: 'ee', type: 'text' },
        ],
      },
    ],
  },
  { uid: 'bb', type: 'text' },
  { uid: 'cc', type: 'text' },
];

There's no limit on how far down it can branch. Realistically we'll want to limit it around 4-5 levels deep, but I was hoping to find an elegant solution and impose limitations on it after, instead of writing it bespoke with 4-5 levels in mind.

At some point the user will want to splice() data into this at a position they specify, using the position (the index ate the current level it should be added to - for example, to add an item before aa, you'd pass index = 0. to add an item inside aa's branch after ff, index = 1), the parents (an array of uids - for example, the item with uid 'gg' would have ['aa', 'dd'] as its parents argument - to get to gg, first you open aa, then you open dd.) and the payload (I've left that out for the sake of the example but you can imagine).

This splice() is where I'm running into trouble as I don't know how far down the 'chain' I have to go or what indexes I have to follow to get there. Using find() and findIndex() I can make an array of indexes (to get to 'gg' this array would look like: let indexes = [0, 2, 0]). However, I'm not able to just data[indexes].splice(...) nor can I find online any way to do that. Also consider that ['branch'] needs to be added between every iteration.

I'm basically hoping for a way to dynamically create, for example, data[0][2][0].

This needs Vue reactivity which is why I'm doing the splice(), very open to ideas though. Additionally, none of this is set in stone (except the structure returned from backend) so if you can think of another way to do this...!

Please let me know if this makes any sense / if you need more info - been struggling with this for a while!

 
Last edited:
Top