How to turn nested objects into array?

Ale*_*yov 2 javascript

I am struggling to what seems to be a trivial task. I need to iterate over this nested object...

[
     {
          "id": "1",
          "name": "Level 1",
          "parent": null,
          "expanded": true,
          "title": "Level 1",
          "children": [
               {
                    "id": "2",
                    "name": "Level 2",
                    "parent": 1,
                    "expanded": true,
                    "title": "Level 2",
                    "children": [
                         {
                              "id": "3",
                              "name": "Level 3",
                              "parent": 2,
                              "expanded": true,
                              "title": "Level 3"
                         }
                    ]
               }
          ]
     }
]
Run Code Online (Sandbox Code Playgroud)

... and end up with below structure.

I have tried .map(Object.values) but that only seems to work partially. What is the most optimal way to get there? What are the alternatives?

 [
  { id: '1', name: 'Level 1', parent: null, expanded: true },
  { id: '2', name: 'Level 2', parent: 1, expanded: true },
  { id: '3', name: 'Level 3', parent: 2, expanded: true }
]
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 6

您可以采用递归方法并将子对象与对象分开,并映射rest对象和平面子对象。

var getFlat = ({ children = [], ...rest }) => [rest, ...children.flatMap(getFlat)],
    data = [{ id: "1", name: "Level 1", parent: null, expanded: true, title: "Level 1", children: [{ id: "2", name: "Level 2", parent: 1, expanded: true, title: "Level 2", children: [{ id: "3", name: "Level 3", parent: 2, expanded: true, title: "Level 3" }] }] }],
    result = data.flatMap(getFlat);

console.log(result)
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)