tengo una matriz de datos
var data=[{ "key": "KUZEY", "items": [ { "key": "MARMARA", "items": [ { "key": "T100", "items": [ { "Ref": 1, "ApprovedReserveQuantity": 1 } ] } ] }, { "key": "MARMARA 2", "items": [ { "key": "T100", "items": [ { "Ref": 2, "ApprovedReserveQuantity": 1 } ] } ] } ] }]Quiero obtener artículos cuando llamo a la función. ¿Cómo se puede hacer ese método recursivo?
elementos agrupados = método recursivo (datos)
elementos agrupados==>[{"Ref": 1,"Cantidad de reserva aprobada": 1},{"Ref": 2,"Cantidad de reserva aprobada": 1}]
groupedItems:any[]=[]; recursiveMethod(element){ if(element.items==null) this.groupedItems.push(element) if (element.items != null){ let i; for(i=0; i < element.items.length; i++){ this.recursiveMethod(element.items[i]); } } }ha funcionado
No se pudo encontrar ninguna verificación de 'clave' en su respuesta. Aunque no confío completamente en mi función, y estoy confundido acerca de por qué funcionó, puede ser reutilizable si lo modifica/ajusta.
const extractInnermostByKey = (data, targetKey, res = []) => { data.forEach((obj) => { for (let key of Object.keys(obj)) { if (key === targetKey) { // console.log(res); observe res res.shift(); res.push(...obj[key]); return extractInnermostByKey(res, targetKey, res); } } }); return res; }; const groupedItems = extractInnermostByKey(data, 'items'); console.log(groupedItems);