So i have for example such an object:
let htmlDom = [ { type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [ { type: "div", content: "test", child: [{}], }, ], }, ];
And now i want to dynamicly acess it, for example: htmlDom[0].child[0].child[0], and now the numbers of children can vary and the numbers generally. lets say for example i have an array of [0, 0, 0], How can i then acess that path dynamicly by using the numbers in the array, and then change the content of the last child[0]? The thing is that for example the array can later on vary to [0,2,4,3,6] and such, and depending on the array lenght i need to create more .child[]
Advertisement
Answer
You can first grab the last index from your array of indexes using .pop()
, and then use .reduce()
on the now modified indexes array to iterate over your children arrays. By setting the accumulator as the starting htmlDom
you can access the objects at each index and its child array for each iteration of .reduce()
, where the child
array from each object is returned. This child array is then used as the acc
for the next call/iteration of your reduce method. Once you have found the last child array, you can use index which you previously popped off your array to set/update the value:
let htmlDom = [ { type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [ { type: "div", content: "test", child: [{}], }, ], }, ]; const changeByIdxs = (arr, [...idxs], value) => { const lastIdx = idxs.pop(); const finalArr = idxs.reduce((acc, i) => acc[i].child, arr); finalArr[lastIdx] = value; } changeByIdxs(htmlDom, [0, 0, 0], {x: 1}); console.log(htmlDom);
The above can be implemented with for loops if you find that easier to understand:
const htmlDom = [{ type: "div", att: { class: ["test", "test2"], id: "yoyo", "data-hello": ["jan", "john"], }, content: "Hello", child: [{ type: "div", content: "test", child: [{}], }, ], }, ]; const changeByIdxs = (arr, [...idxs], value) => { const lastIdx = idxs.pop(); let finalArr = arr; for (let i = 0; i < idxs.length; i++) { const idx = idxs[i]; finalArr = finalArr[idx].child; } finalArr[lastIdx] = value } changeByIdxs(htmlDom, [0, 0, 0], {x: 1}); console.log(htmlDom);