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

112
Vistas
Is Array has a node element ? Js

I need to go through the array and find out if my array has children elements. Example any time i got array like a:

[
 id: 1,
 title: 'Parent',
 children : [
 {
   id: 13,
   title: 'Child'
 }
]

any time i got array:

[
 id: 1,
 title: 'Parent',
 children : [
 {
   id: 13,
   title: 'Child'
 },
 {
   id: 14,
   title: 'Child two'
 }
]

To explain better. The elements have their parent, child elements. What is my task? I need to find all the elements I get and put them in a array separately. So I need to extract these child elements from the array and put them in one array where all the elements are.

After looping of above array i need to get new array like:

FROM:

[
 id: 1,
 title: 'Parent',
 children : [
 {
   id: 13,
   title: 'Child'
 },
 {
   id: 14,
   title: 'Child two'
 }
]

TO

[
 {
   id: 1,
   title: 'Parent', 
 },
 {
   id: 13,
   title: 'Child'
 },
 {
   id: 14,
   title: 'Child two'
 }
]
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Here is another recursive way of doing it:

The outer function collect(arr) provides a scope for the inner recursively called function getItems(). Whenever a child item is found the properties id and title are assembled into a new object and pushed into the results array res that was defined in collect().

const data=[{id:1,
             title:'Parent',
             children:[{id:13,
                        title:'Child'},
                       {id:14,
                        title:'Child two',
                        children: [{id:15,
                                    title:'Grandchild'}] 
                       }]},
             {id:16,
              title:'Uncle'}
           ];
           
function collect(arr){
 const ret=[];
 function getItems(ob){
   ret.push({id:ob.id,title:ob.title});
   if (ob.children) ob.children.forEach(getItems);
 }
 arr.forEach(getItems)
 return ret
}

console.log(collect(data))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another one solution:

const data = [{"id":1,"title":"Parent","children":[{"id":13,"title":"Child"},{"id":14,"title":"Child two"}]}];

const flatObj = (arr) => arr.reduce((acc, { id, title, children }) => ([
  ...acc,
  ...(children) ? [{ id, title }, ...flatObj(children)] : [{ id, title }]
]), []);

console.log(flatObj(data));
.as-console-wrapper{min-height: 100%!important; top: 0}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Given an array of objects where an object will always have id, title and may or may not have the prop children, the stated/assumed objective is to transform this array into an array which only has id and title (including the children's id, title).

Sample Code

const getIdTitles = arr => (
    arr.reduce(
    (f, i) => (
        {
        ...f,
        [i.id] : i.title,
        ...(
            'children' in i
            ? getIdTitles(i.children)
            : {}
           )
      }
    ),
    {}
  )
);

Approach

  • The idea is to use a recursive method
  • Iterate through the given array using reduce
  • Use ... spread-operator to first spread contents of the aggregator f
  • Next, add the current array element's id and title
  • Then, if the current element contains children then recurse

Code Snippet

const someArray = [{
 id: 1,
 title: 'Parent',
 children : [
 {
   id: 13,
   title: 'Child'
 },
 {
   id: 14,
   title: 'Child two'
 }
 ]
}];

const getIdTitles = arr => (
    arr.reduce(
    (f, i) => (
        {
        ...f,
        [i.id] : i.title,
        ...(
            'children' in i
            ? getIdTitles(i.children)
            : {}
           )
      }
    ),
    {}
  )
);

console.log(getIdTitles(someArray))

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