How to get the last children in a deeply nested array with objects

Tags: , ,



So let’s say I have a deeply nested array and I want to get the deepest nested children and I’m unable to think of a good way to implement it

basically as long as the children property exists, it needs to dive inside it and it not I want to test if the name matches my search

[
 {
  name: 'something',
  children: [
   {
    name: 'something',
    children: [
     {
      ...
     }
    ]
   }
  ]
 },
 {
  name: 'something',
  children: [
   {
    name: 'something',
    children: [
     {
      ...
     }
    ]
   }
  ]
 },
]

Answer

hasOwnProperty() may help you knowing if the property Children exist or not, and then, knowing if you need a recursive call or not

For example :

var MyObj = [
 {
  name: 'something',
  children: [
   {
    name: 'something',
    children: [
     {
      name: 'no child'
     },
     {
      name: 'something empty',
      children: [ ]
     }
    ]
   }
  ]
 },
 {
  name: 'something',
  children: [
   {
    name: 'something',
    children: [
     {
      name: 'no child'
     }
    ]
   }
  ]
 },
 {
    name: "children isn't an array",
    children: 42
 }
]

/*
 * This will display in the console the "name" property, if it exists,
 * of elements that has :
 *  - no "children" property
 *  - a "children" property that isn't an array
 *  - a "children" property that is an empty array
 */
function ChildrenNames(obj)
{
  obj.forEach((subObj) => 
  {
    if (subObj.hasOwnProperty('children')
        && subObj.children instanceof Array
        && subObj.children.length > 0)
    {
      ChildrenNames(subObj.children);
    }
    else
    {
      if (subObj.hasOwnProperty('name'))
        console.log(subObj.name);
    }
  });
}

ChildrenNames(MyObj);


Source: stackoverflow