亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為嵌套對象數組中的子對象添加值

如何為嵌套對象數組中的子對象添加值

ABOUTYOU 2023-09-28 17:41:03
我有一個嵌套的對象數組,我需要動態更改子數據的值[    {        type: "root",        title: "FileManager",        isDirectory: true,        children: [            {                type: "folder",                title: "animals",                isDirectory: true,                children: [                    {                        type: "folder",                        title: "cat",                        isDirectory: true,                        children: [                            {                                type: "folder",                                title: "images",                                isDirectory: true,                                children: [                                    {                                        type: "file",                                        title: "cat001.jpg",                                        isDirectory: false,                                    }, {                                        type: "file",                                        title: "cat002.jpg",                                        isDirectory: false,                                    }                                ]                            }                        ]                    }                ]            },            {                type : "folder",                title : 'Birds',                isDirectory : true,                children : []            }        ]    }]這是我的主要對象數組,假設我想動態更改子對象的值。假設我想向圖像數組中的子對象添加一個對象,因此圖像數組的路徑是 FileManager / Animals / cat / images 如何動態更改圖像對象中子對象的值?
查看完整描述

1 回答

?
幕布斯6054654

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 :)

如果此答案可以幫助您解決問題,請考慮接受答案或投票。謝謝。


查看完整回答
反對 回復 2023-09-28
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號