Supongamos que tengo una lista de matrices de objetos como a continuación
[ {id:1,parent:0,name:"test 1",subs:[3,4]}, {id:2,parent:0,name:"test 2",subs:[5,6]}, {id:3,parent:1,name:"test 3",subs:[7]}, {id:4,parent:1,name:"test 4",subs:[]}, {id:5,parent:2,name:"test 5",subs:[]}, {id:6,parent:2,name:"test 6",subs:[8]}, {id:7,parent:3,name:"test 7",subs:[]}, {id:8,parent:6,name:"test 8",subs:[]}, ]ahora quiero hacer una matriz de cadenas de nombres con posibles nombres de subs
si considera la matriz anterior, la salida debería ser como la siguiente
[ "test 1", "test 1 - test 3", "test 1 - test 4", "test 1 - test 3 - test 7", "test 2", "test 2 - test 5", "test 2 - test 6", "test 2 - test 6 - test 8" ]Por favor ayúdenme con la solución. Gracias de antemano
Esta solución construye un árbol e itera a los niños.
const data = [{ id: 1, parent: 0, name: "test 1", subs: [3, 4] }, { id: 2, parent: 0, name: "test 2", subs: [5, 6] }, { id: 3, parent: 1, name: "test 3", subs: [7] }, { id: 4, parent: 1, name: "test 4", subs: [] }, { id: 5, parent: 2, name: "test 5", subs: [] }, { id: 6, parent: 2, name: "test 6", subs: [8] }, { id: 7, parent: 3, name: "test 7", subs: [] }, { id: 8, parent: 6, name: "test 8", subs: [] }], getTree = (data, root) => { const t = {}; data.forEach(o => ((t[o.parent] ??= {}).children ??= []).push(Object.assign(t[o.id] ??= {}, o))); return t[root].children; }, flat = p => o => (name => [ name, ...(o.children || []).flatMap(flat(name)) ])(p + (p && ' - ') + o.name), tree = getTree(data, 0), result = tree.flatMap(flat('')); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } Un enfoque mediante el uso de subs y un objeto de referencias por id .
const data = [{ id: 1, parent: 0, name: "test 1", subs: [3, 4] }, { id: 2, parent: 0, name: "test 2", subs: [5, 6] }, { id: 3, parent: 1, name: "test 3", subs: [7] }, { id: 4, parent: 1, name: "test 4", subs: [] }, { id: 5, parent: 2, name: "test 5", subs: [] }, { id: 6, parent: 2, name: "test 6", subs: [8] }, { id: 7, parent: 3, name: "test 7", subs: [] }, { id: 8, parent: 6, name: "test 8", subs: [] }], root = [], ids = Object.fromEntries(data.map(o => [o.id, (o.parent|| root.push(o.id), o)])), flat = p => id => (name => [ name, ...ids[id].subs.flatMap(flat(name)) ])(p + (p && ' - ') + ids[id].name), result = root.flatMap(flat('')); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }