1 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
根據(jù)提供的數(shù)據(jù)結(jié)構(gòu),您可以使用遞歸解決方案來(lái)到達(dá)您感興趣的嵌套數(shù)組,然后當(dāng)遞歸命中時(shí),base case您可以將新對(duì)象推入該特定深度級(jí)別的數(shù)組中,或者使用一個(gè)回調(diào)函數(shù),將盡可能多的新對(duì)象推入其中。
我不太確定您所指的“動(dòng)態(tài)”部分,但以下內(nèi)容應(yīng)該使您朝著正確的方向前進(jìn):
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 :)
如果此答案可以幫助您解決問(wèn)題,請(qǐng)考慮接受答案或投票。謝謝。
添加回答
舉報(bào)