Guys, there was a question about navigating through an array (it would seem!). The search failed, because hesitate and do not understand how to ask a question.

In general the task.

I make the component of the drag and drop tree on vue by the example of the react component

VueNestable

VueNestable

data structure - an array of objects with nested child arrays, etc.

// примерная структура const items = [ { _path: [0], title: "[0]", children:[ { _path: [0,0], title: "[0,0]", children: [] }, { _path: [0,1], title: "[0,1]", children: [ { _path: [0,1,0], title: "[0,1,0]", children: [/* ... */] } ] }, ] }, /* ... */ ] 

Nesting may be different. The element has the _path parameter - an array with its "address" in the strut. How to most beautifully refer to an element by its _path ?

For example, from any source we get _path=[0,2] , as you understand, in the code to write items[_path[0]].children[_path[1]] is not at all an option. And if the depth is 5 or 10? I would be grateful for any advice))

    1 answer 1

     function getElement(tree, path) { return getElement(tree[path.shift()].children, path); } 

    Just be sure to clone the path before calling the function, since arrays are passed by reference, and the function changes the path passed to it.

    Well, I would add parameter checks if there is a likelihood of invalid data in the tree itself.

    • Thanks for the tip)) Another small question (already undermining). How to replace the entire root element now (this is Vue reactivity support). I suppose it is necessary to clone the root object with the entire structure, get to the last object in the tree, make changes and replace the root element with splice() - Maxim By
    • @Maxik, unfortunately did not work with Vue. I do not really understand what needs to be done. - Mike Papou
    • Well, okay)) And thanks for that.)) - Maxim K