Hola a todos tengo los siguientes datos:
const section = { fileds: [ { id: "some Id-1", type: "user-1" }, { child: [ { id: "some Id-2", type: "user-2" }, { fileds: [{ id: "kxf5", status: "pending" }] }, { fileds: [{ id: "ed5t", status: "done" }] } ] }, { child: [ { id: "some Id-3", type: "teacher" }, { fileds: [{ id: "ccfr", status: null }] }, { fileds: [{ id: "kdpt8", status: "inProgress" }] } ] } ] };y siguiente código:
const getLastIds = (arr) => arr.flatMap((obj) => { const arrayArrs = Object.values(obj).filter((v) => Array.isArray(v)); const arrayVals = Object.entries(obj) .filter(([k, v]) => typeof v === "string" && k === "id") .map(([k, v]) => v); return [...arrayVals, ...arrayArrs.flatMap((arr) => getLastIds(arr))]; }); console.log(getLastIds(section.fileds)); // output is (7) ["some Id-1", "some Id-2", "kxf5", "ed5t", "some Id-3", "ccfr", "kdpt8"]Mi código está haciendo lo siguiente, imprimiendo en una nueva matriz todos los identificadores.
Está funcionando, pero no necesito todas las identificaciones.
Necesito devolver solo la última id en la matriz y debería usar la recursividad. La salida debe ser
(4) [" "kxf5", "ed5t", "ccfr", "kdpt8"]
PD aquí está mi código en codesandbox
¿Hay alguna manera de resolver este problema con la recursividad? Por favor, ayuda a arreglar esto.
Puedes hacerlo con reduce .
function getLastIds (value) { return value.reduce((prev, cur) => { if (cur.id) { return [ ...prev, cur.id ]; } else { let key = ('child' in cur) ? 'child' : 'fileds'; return [ ...prev, ...getLastIds (cur[key]) ] } }, []); }Puede verificar si existe una determinada clave y tomar esta propiedad para mapear la id si existe status .
const getValues = data => { const array = Object.values(data).find(Array.isArray); return array ? array.flatMap(getValues) : 'status' in data ? data.id : []; }, section = { fileds: [{ id: "some Id-1", type: "user-1" }, { child: [{ id: "some Id-2", type: "user-2" }, { fileds: [{ id: "kxf5", status: "pending" }] }, { fileds: [{ id: "ed5t", status: "done" }] }] }, { child: [{ id: "some Id-3", type: "teacher" }, { fileds: [{ id: "ccfr", status: null }] }, { fileds: [{ id: "kdpt8", status: "inProgress" }] }] }] }, result = getValues(section); console.log(result);