I have a rootArray with some nested arrays, it could be any depth.
I want to dynamically access a certain inner array, defined by a list of indexes, to push new content there.
so for example, if the list of index is
currentFocusedArray = [1,2]
i want to…
rootArray[1][2].push('new content')
dynamically, not hardwired.
Maybe this is a case of the trees not letting me see the forest or maybe I am on a dead end.
I am just making a note taking simple app, with react, very simple yet.
Any advice is welcome!
Hopefully I didnt waste your time. Thanks in advance.
Simple answer would be don’t: give each node an ID, then select based on ID. So don’t have a list of notes, have an object which has the notes keyed by ID:
{
1: {
id: 1,
children: [2]
parent: null,
text: "Imma note"
},
2: {
id: 2,
children: [3, 4]
parent: 1,
text: "'nother note"
},
...etc
}
Then a list of top-level note IDs:
[1, 5, ...etcetc]
Loop through the top-level notes, render. For each one, check if they have children, render, etc.
Each note has an ID, so where they are in the tree doesn’t matter when you’re selecting them.
Nested objects (particularly arrays) are pretty painful to work with, so always try to flatten them; single-dimensional things are generally much easier to deal with, but you need to think carefully about how you build and connect the items.
(Note it’s generally useful to do this with lists of stuff in React – flat list of IDs + flat object of {id: data}
)
1 Like
Oh thanks a lot I guess this is more professional and more database friendly. A million thanks. I want to buy you a coffee.
1 Like
Hope it’s helpful! Trying to drill through arrays dynamically is quite hard – it’s more than doable, but you’re going to probably want to reach for recursion, which gets mindbending, and anyway JS isn’t very good at that. It’s good that you recognised the database thing: what I was describing is just normalisation of data – there’s a good overview in the Redux docs (not that you need to use Redux at all) that might be a useful read:
1 Like