Reputation: 43
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.
https://codesandbox.io/embed/quirky-gauss-09i1h
Any advice is welcome! Hopefully I didnt waste your time. Thanks in advance.
Upvotes: 1
Views: 1876
Reputation: 122047
You could use reduce
to create such function that will set nested array element on any level.
const rootArray = []
function set(arr, index, value) {
index.reduce((r, e, i, a) => {
if (!r[e]) {
if (a[i + 1]) r[e] = []
} else if (!Array.isArray(r[e])) {
if (a[i + 1]) {
r[e] = [r[e]]
}
}
if (!a[i + 1]) {
if (Array.isArray(r)) {
r[e] = value
}
}
return r[e]
}, arr)
}
set(rootArray, [1, 2], 'foo');
set(rootArray, [1, 1, 2], 'bar');
set(rootArray, [1, 2, 2], 'baz');
console.log(JSON.stringify(rootArray))
Upvotes: 0
Reputation: 31625
You can make it with a for loop.
let myArray = rootArray
for(let i = 0; i < currentFocusedArray.length; i++){
myArray = myArray[currentFocusedArray[i]]
}
After this, you will have myArray
reference the deep nested value of rootArray
.
let rootArray = {
"1": {
"2": []
}
}
let currentFocusedArray = [1, 2]
let myArray = rootArray
for(let i = 0; i < currentFocusedArray.length; i++){
myArray = myArray[currentFocusedArray[i]]
}
myArray.push("new content")
console.log(myArray)
Upvotes: 0
Reputation: 6869
You can write find array to get array based on your focus array. Use array method reduce to find node from an array of indexes
var updateNode = focus.reduce((node,index) => node && node[index], notes);
updateNode && updateNode.push("new content");
Upvotes: 1