为了账号安全,请及时绑定邮箱和手机立即绑定

如何为嵌套对象数组中的子对象添加值

如何为嵌套对象数组中的子对象添加值

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 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信