1 回答

TA貢獻1876條經驗 獲得超7個贊
根據提供的數據結構,您可以使用遞歸解決方案來到達您感興趣的嵌套數組,然后當遞歸命中時,base case您可以將新對象推入該特定深度級別的數組中,或者使用一個回調函數,將盡可能多的新對象推入其中。
我不太確定您所指的“動態”部分,但以下內容應該使您朝著正確的方向前進:
function rec(array) {
for (let i in array) {
if (array[i].children === undefined) { // BASE CASE
// console.log("base case ", array);
// push the object you want into the array, as at this point in the
// recursion you will be at the level you can modify your image array as you like
return array.push({ "myImage": "myBeautifulCatImage", "does": "poooooor"});
}
// recursive call
// visualise how deep you are going...
// console.log("rec", array[i].children);
return rec(array[i].children);
}
}
rec(arr);
// if you know log your arr as in:
// console.log("arr after recursion", rec(arr))
// you will see your new cat showing where it should be :)
如果此答案可以幫助您解決問題,請考慮接受答案或投票。謝謝。
添加回答
舉報