来个 js 算法大牛看看这个题,有没有优雅点的代码?
`源数据`
```
const data = [
  {
    city:'浙江',
    children:[
      {
        city:'宁波',
        children:[{
          city:'鄞州区',
          children:[]
        },{
          city:'江北区',
          children:[]
        }]
      },
      {
        city:'杭州',
        children:[{
          city:'富阳',
          children:[]
        },{
          city:'上城区',
          children:[]
        }]
      }
    ]
  },
  {
    city:'上海',
    children:[
      {
        city:'黄浦区',
        children:[]
      }
    ]
  }
]
```
`目标结构`
```
[
  "浙江,宁波,鄞州区",
  "浙江,宁波,江北区",
  "浙江,杭州,富阳",
  "浙江,杭州,上城区",
  "上海,黄浦区"
]
```
## solution 1
```
function flatTree(nodes, parents = []) {
    const pathes = nodes
        .filter(({ children }) => !children?.length)
        .map(({ city }) => [...parents, city]);
    const subPathes = nodes.filter(({ children }) => children?.length)
        .flatMap(({ city, children }) => flatTree(children, [...parents, city]));
    return pathes.concat(subPathes);
}
```
## solution 2
```
function flatTree(nodes, parents = []) {
    return nodes.flatMap(({ city, children }) => {
        return children?.length
            ? flatTree(children, [...parents, city])
            : [[...parents, city]];
    });
}
```
## using
```
console.log(flatTree(data).map(path => path.join(",")));
//                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
```