假设我有一个深层嵌套的数组,我想获得最深层的嵌套子级,但我想不出实现它的好方法

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

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

最佳答案

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

关于javascript - 如何在对象的深层嵌套数组中获取最后一个 child ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56756192/

10-08 22:48