'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'
 }
]


Solution 1:[1]

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))

Solution 2:[2]

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}

Solution 3:[3]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 A1exandr Belan
Solution 3 jsN00b