如何在对象的深层嵌套数组中获取最后一个孩子

时间:2019-06-25 14:19:15

标签: javascript reactjs recursion

所以说我有一个嵌套很深的数组,我想得到嵌套最深的子对象,而我想不出实现它的好方法

基本上,只要children属性存在,它就需要潜入其中,并且我不想测试名称是否与我的搜索匹配

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

1 个答案:

答案 0 :(得分:4)

hasOwnProperty()可能会帮助您了解属性Children是否存在,然后知道您是否需要递归调用

例如:

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