Javascript递归:删除只有一个孩子的关卡 [英] Javascript Recursion: remove level with only one child

查看:45
本文介绍了Javascript递归:删除只有一个孩子的关卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下数据结构:

[  
  {  
     "name":"root",
     "children":[  
        {  
           "name":"de",
           "children":[  
              {  
                 "name":"de",
                 "children":[
                    {  
                       "name":"project-1",
                       "children":[  
                       ]
                    },
                    {  
                       "name":"project-2",
                       "children":[  
                       ]
                    }
                 ]
              }
           ]
        }
     ]
  }
]

预期:

[
  {
     "name":"project-1",
     "children":[
     ]
  },
  {
     "name":"project-2",
     "children":[
     ]
  }
]

如果只有一个孩子,我想删除一个关卡.在此示例中,我想要一个新数组,其中仅包含"root"级别的子级,而没有root本身.

I want to remove a level if there is only one child. In this example I want to have a new array that only contains the children of the "root" level without root itself.

我会用 reduce 来做到这一点,但仍然无法结合递归结合在 reduce 上.有什么想法吗?

I would do that with reduce but still cant wrap my head around reduce in combination with recursion. Any ideas?

推荐答案

之后,您可以简单地使用map和flatten数组.

You can simply use map and flatten arrays afterwards.

.map(o => o.children).flat()

找出真实问题后,更新答案
您仍然可以以递归的方式使用map和flatten逻辑.

updated answer after figuring out the real question
Still you can use map and flatten logic but in a recursive manner.

function removeSingleChildElms (o) {
  if (!o.children) return

  if (o.children.length === 1) {
      return o.children.map(removeSingleChildElms).flat()
  } else {
    return o.children
  }
}

一些解释:问题是将对象数组转换为不同对象的数组.我不选择减少,因为问题不在乎同级元素之间的关系/逻辑.这只是为了进行转换,因此地图将足以正常工作.

Some explanation: The problem is transforming array of object(s) into array of different objects. I don't choose reduce, because the problem doesn't care about relationship/logic among sibling elements. It's just about transforming, hence map will just work good enough.

问题要求跳过"有1个孩子的对象.这是重复出现的部分,其含义是:如果看到满足此条件的对象,则可以进行更深入的映射.在任何其他有效条件下,孩子都保持不变(否则)

The problem asks to 'skip' objects with 1 child. This is recurring part, meaning: If you see an object satisfying this condition you go deeper for mapping. In any other valid condition, children stay same (else case)

这篇关于Javascript递归:删除只有一个孩子的关卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆