entonces tengo la siguiente estructura de árbol:
const tree = { id: "1", tag: "pending", subtasks: [ { id: "2", tag: "pending", subtasks: [] }, { id: "3", tag: "in progress", subtasks: [ { id: "4", tag: "pending", subtasks: [ { id: "6", tag: "in progress", subtasks: [ { id: "10", tag: "pending", subtasks: [{ id: "11", tag: "complete", subtasks: [] }] } ] }, { id: "7", tag: "complete", subtasks: [] } ] }, { id: "5", tag: "pending", subtasks: [] } ] }, { id: "4", tag: "complete", subtasks: [] } ] }; y quiero eliminar cualquier nodo que tenga la tag "en progreso". Pero también quiero mantener a los elementos secundarios del nodo eliminado si sus tag no están "en progreso". Se mantendrán moviéndolos a la misma profundidad y niveles de índice de su padre.
entonces, el resultado será algo como esto:
const filteredTree = { id: "1", tag: "pending", subtasks: [ { id: "2", tag: "pending", subtasks: [] }, { id: "4", tag: "pending", subtasks: [ { id: "10", tag: "pending", subtasks: [{ id: "11", tag: "complete", subtasks: [] }] }, { id: "7", tag: "complete", subtasks: [] } ] }, { id: "5", tag: "pending", subtasks: [] }, { id: "4", tag: "complete", subtasks: [] } ] };¿Cómo puedo lograr eso?
Puede eliminar marcando tag y tomar las subtasks filtradas o un nuevo objeto con subtasks filtradas.
const remove = tag => ({ subtasks, ...node }) => { subtasks = subtasks.flatMap(remove(tag)); return node.tag === tag ? subtasks : [{ ...node, subtasks }] }, tree = { id: "1", tag: "pending", subtasks: [ { id: "2", tag: "pending", subtasks: [] }, { id: "3", tag: "in progress", subtasks: [{ id: "4", tag: "pending", subtasks: [{ id: "6", tag: "in progress", subtasks: [{ id: "10", tag: "pending", subtasks: [{ id: "11", tag: "complete", subtasks: [] }] }] }, { id: "7", tag: "complete", subtasks: [] }] }, { id: "5", tag: "pending", subtasks: [] }] }, { id: "4", tag: "complete", subtasks: [] }] }, result = remove('in progress')(tree); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }