Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
Return necessary value with recursion - Javascript

I have following data:

    const section={
     fileds: [
     {
      child: [
        {
          fileds: [
            {
              id: "kxf5",
              label: null
            }
          ]
        },
        {
          fileds: [
            {
              id: "ed5t",
              label: "section"
            }
          ]
        },
        
      ]
    },
    {
      child: [
        {
          fileds: [
            {
              id: "ccfr",
              label: null
            }
          ]
        },
        {
          fileds: [
            {
              id: "kdpt8",
              label: "section"
            }
          ]
        },
        
      ]
    },
    
     ]
    }

I need to return all id in array and I should use recursion.

I have try following code.

const section={fileds: [{child: [{fileds: [{id: "kxf5",label: null}]},{fileds: [{id: "ed5t",label: "section"}]},]},{child: [{fileds: [{id: "ccfr",label: null}]},{fileds: [{id: "kdpt8",label: "section"}]},]},]}
function printId(value, child ) {
  return [value, ...(child ? printList(child) : [])]
}

console.log(printId(section.fields));

But it not helped me.

Is there a way to solve this problem with recursion? Please help to fix this.

The final result should be like ["kxf5","ed5t","ccfr", "kdpt8"] this.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

An other way, using reduce() to recursively fill an array

const section= {fileds: [{child: [{fileds: [{id: "kxf5", label: null } ] }, {fileds: [{id: "ed5t", label: "section"} ] }, ] }, {child: [{fileds: [{id: "ccfr", label: null } ] }, {fileds: [{id: "kdpt8", label: "section"} ] }, ] }, ] }

function printId(value) {
    return value.reduce((prev, cur) => {
        if (cur.id) {
            return [ ...prev, cur.id ];
        } else {
            let key = ('child' in cur) ? 'child' : 'fileds';
            return [ ...prev, ...printId(cur[key]) ]
        }
    }, []);
}

console.log(printId(section.fileds));

about 4 years ago · Juan Pablo Isaza Denunciar

0

A better solution could be this one:

// recursive method to extract "id"s
function getId(o) {
  // if current parameter "o" has "id" prop, return it
  if (o.id) return o.id;
  // else, iterate over "o" and recurse for each "value" of "o"
  return Object.keys(o).flatMap((key) => getId(o[key]));
}
const section = {
  fileds: [{
      child: [{
          fileds: [{
            id: "kxf5",
            label: null
          }]
        },
        {
          fileds: [{
            id: "ed5t",
            label: "section"
          }]
        },

      ]
    },
    {
      child: [{
          fileds: [{
            id: "ccfr",
            label: null
          }]
        },
        {
          fileds: [{
            id: "kdpt8",
            label: "section"
          }]
        },

      ]
    },

  ]
};

console.log(getId(section));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Below is one possible way to achieve the target.

Code Snippet

// recursively get only "id"s
const getIds = arr => (
  // implicit return of below result
  // iterate using ".flatMap()" to avoid nested result
  arr.flatMap(obj => {
    // extract values that are arrays
    const arrArrs = Object.values(obj).filter(v => Array.isArray(v));
    // extract values for key "id"
    const arrVals = Object.entries(obj).filter(
      ([k, v]) => typeof v === 'string' && k === "id"
    ).map(([k, v]) => v);
    // return "id" values, and then recursively call getIds for each "ar" (array)
    return [...arrVals, ...arrArrs.flatMap(ar => getIds(ar))]
  })
);

const section = {
  fileds: [{
      child: [{
          fileds: [{
            id: "kxf5",
            label: null
          }]
        },
        {
          fileds: [{
            id: "ed5t",
            label: "section"
          }]
        },

      ]
    },
    {
      child: [{
          fileds: [{
            id: "ccfr",
            label: null
          }]
        },
        {
          fileds: [{
            id: "kdpt8",
            label: "section"
          }]
        },

      ]
    },

  ]
};

console.log(getIds(section.fileds));

Explanation

Inline comments added in the snippet above.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda