Как удалить элементы из массива многомерных массивов - PullRequest
0 голосов
/ 14 января 2020

Мне нужна помощь по удалению элементов из TreeView (это проект Vue. js), TreeView построен на основе такого элемента:

[
    {
        "id": 1,
        "name": "COMERCIALIZAÇÃO",
        "idp": "",
        "children": [
            {
                "id": 5,
                "name": "Pasta 1",
                "idp": 1,
                "children": [
                    {
                        "id": 6,
                        "name": "Pasta 1 2",
                        "idp": 5,
                        "children": [
                            {
                                "id": 7,
                                "name": "NO.FT.DRC.01.00.001.pdf",
                                "file": "pdf",
                                "idp": 6
                            },
                            {
                                "id": 8,
                                "name": "PR.FT.DRC.01.00.003.pdf",
                                "file": "pdf",
                                "idp": 6
                            }
                        ]
                    },
                    {
                        "id": 9,
                        "name": "imprimir p luiza.pdf",
                        "file": "pdf",
                        "idp": 5
                    },
                    {
                        "id": 66,
                        "name": "Pasta 1 3",
                        "idp": 5,
                        "children": [
                            {
                                "id": 77,
                                "name": "NO.FT.DRC.01.00.001.pdf",
                                "file": "pdf",
                                "idp": 66
                            },
                            {
                                "id": 88,
                                "name": "PR.FT.DRC.01.00.003.pdf",
                                "file": "pdf",
                                "idp": 66
                            }
                        ]
                    }
                ]
            },
            {
                "id": 10,
                "name": "Backend.docx",
                "file": "pdf",
                "idp": 1
            },
            {
                "id": 0,
                "name": "DT.DC.RPI.03.03.1235_V2.docx",
                "file": "pdf",
                "idp": 1
            }
        ]
    },
    {
        "id": 2,
        "name": "DISTRIBUIÇÃO",
        "idp": "",
        "children": [
            {
                "id": 11,
                "name": "Pasta 2",
                "idp": 2,
                "children": [
                    {
                        "id": 12,
                        "name": "pasta 2 1",
                        "idp": 11,
                        "children": [
                            {
                                "id": 13,
                                "name": "script.sql",
                                "file": "pdf",
                                "idp": 12
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "id": 3,
        "name": "GERAÇÃO",
        "idp": "",
        "children": [
            {
                "id": 14,
                "name": "Pasta 3",
                "idp": 3
            }
        ]
    },
    {
        "id": 4,
        "name": "SERVIÇOS",
        "idp": "",
        "children": [
            {
                "id": 5,
                "name": "teste",
                "idp": 4
            }
        ]
    }
]

I ' Я не уверен, но я думаю, что лучший способ описать этот элемент: массив многомерных массивов, верно?

Я создал CodePen, чтобы показать наиболее близкий результат, полученный при использовании рекурсивности, но, конечно, мой нет не лучшее решение, так как оно не работает при каждом удалении. Посмотрите на мой код: https://codepen.io/luizarusso/pen/zYxLOPb?editors=1010

for (let i = 0; i < items.length; i++) {
    if (items[i].id == item.id) {
        //se achou o cara que vai ser removido, chama a função de remover
        return this.removeItem(i);
    } else {
        if (items[i].children) {
            if (items[i].idp == "") {
                this.caminho = [];
            }
            this.caminho.push(i);
            this.delFile(item, items[i].children);
        } else {
            if (items.length == 1 + i) {
                this.caminho.pop();
            }
        }
    }
}

Есть идеи? Не стесняйтесь оптимизировать мой код непосредственно на CodePen, если вы предпочитаете:)

РЕДАКТИРОВАТЬ: просто чтобы уточнить, моя проблема здесь заключается исключительно в том, как удалить элемент по идентификатору. Когда пользователь нажимает на значок корзины, я знаю, какой элемент мне нужно удалить, но я не знаю, как извлечь его из массива. Функции Map, Filter и другие встроенные функции JS не могут сделать это с массивом массивов / JSON, поэтому я подумал об использовании рекурсивности или чего-то еще, чтобы это работало.

Ответы [ 2 ]

0 голосов
/ 17 января 2020

Проблема была в том, где я поместил this.caminho.pop()

. Я должен делать это только в «другом» условии, которое сравнивает идентификатор текущего элемента с идентификатором элемента, который я нахожусь. ищу.

delFile(item, items) {
    for (let i = 0; i < items.length; i++) {
        if (items[i].id == item.id) {
            //if the current item has the same id as the item I'm looking for
            //it means I found the guy and I call the function to remove it
            return this.removeItem(i);
        } else {
            //otherwise, I keep on searching
            if (items[i].children) {
                //if the item on the actual index have children, I'll search among them
                if (items[i].idp == "") {
                    //if the items doesn't have a parent, I clean the "caminho" (path) var. That var traces the route till the item I'm looking for
                    this.caminho = [];
                }
                //I push the index to the var that traces the route
                this.caminho.push(i);
                //I call the function back again, now with the child items
                this.delFile(item, items[i].children);
            }
            if (items.length == 1 + i) {
                //if the item's lenght has been completely coursed, I pop the index out of the var that holds the route, because at this point I know the item I'm looking for is not among them
                this.caminho.pop()
            }
        }
    }
},

Вот решение: https://codepen.io/luizarusso/pen/zYxLOPb Работает с деревом с любой глубиной

0 голосов
/ 14 января 2020

Вам нужно смотреть на объекты, а не только на массивы. Позвольте мне рекомендовать пример библиотеки. https://github.com/leezng/vue-json-pretty.

Если ваш вопрос об итерации и обработке многомерного массива, я думаю, вам нужно задать теги javascript и / или алгоритма. Я надеюсь, что этот ответ поможет вам.

...