javascript重新计算深度嵌套的数组元素数

我得到以下数组:


let data =  [

        {"title": {number: 1},

            "children": [

                {"title": {number: 1.1}},

                {"title": {number: 1.2}},

                {"title": {number: 1.3}},

                {"title": {number: 1.4}},

                {"title": {number: 1.5}}

            ]

        },

        {"title": {number: 2},

            "children": [

                {"title":{number: 2.1}},

                {"title":{number: 2.2},

                    "children": [

                        {"title":{number: 2.2.1}},

                        {"title":{number: 2.2.2}},

                        {"title":{number: 2.2.3}},

                        {"title":{number: 2.2.4}} 

                    ]

                },

                {"title":{number: 2.3}},

                {"title":{number: 2.4}}

            ]

        },

        {"title": {number: 3},

            "children": []

        }

    ];

这个数组的每个元素都可以改变它的位置,可以添加新元素,可以删除现有元素。任务是重新计算元素编号以保持其正确顺序。例如,如果2.2.2删除了带有数字的元素,则其他元素变为2.2.1,2.2.2和2.2.3。如果某个元素连同其子元素一起被移除,则所有其他元素的数字也应重新计算。欢迎任何想法如何做到这一点。谢谢


米琪卡哇伊
浏览 116回答 1
1回答

一只甜甜圈

您可以创建递归函数,每次您的对象结构更改时都会调用该函数以重新计算树中每个元素的位置。function recalc(data, prev = '') {  data.forEach((e, i) => {    let dot = prev ? '.' : '';    let number = prev + dot + (i + 1);    if (e.children) {      recalc(e.children, number)    }    if (e.title) {      e.title.number = number    }  })}const data1 = [{"title":{"number":1},"children":[{"title":{"number":1.1}},{"title":{"number":1.2}},{"title":{"number":1.3}},{"title":{"number":1.4}},{"title":{"number":1.5}}]},{"title":{"number":2},"children":[{"title":{"number":2.1}},{"title":{"number":2.2},"children":[{"title":{"number":"2.2.1"}},{"title":{"number":"2.2.2"}},{"title":{"number":"2.2.3"}},{"title":{"number":"2.2.4"}}]},{"title":{"number":2.3}},{"title":{"number":2.4}}]},{"title":{"number":3},"children":[]}]recalc(data1);console.log(data1)const data2 = [{"title":{"number":1},"children":[{"title":{"number":1.1}},{"title":{"number":1.2}},{"title":{"number":1.5}}]},{"title":{"number":2},"children":[{"title":{"number":2.1}},{"title":{"number":2.2},"children":[{"title":{"number":"2.2.3"}},{"title":{"number":"2.2.4"}}]},{"title":{"number":2.3}},{"title":{"number":2.4}}]},{"title":{"number":3},"children":[{title: {}, children: [{title: {}}, {title: {}}]}]}]recalc(data2);console.log(data2)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript