How does js tile the tree structure?

how to tile a tree-structured array into a normal array?

related codes

cost treeNode = [{
    parentId: 0,
    title: "1",
    id:1,
    children: [{
       parentId: 1,
       title: "1-1",
       id:22, 
    },{
       parentId: 1,
       title: "1-2",
       id:33, 
    }],
},{
    parentId: 0,
    title: "2",
    id:2,
    children: [{
       parentId: 2,
       title: "2-1",
       id:44, 
    },{
       parentId: 1,
       title: "2-2",
       id:55, 
    }],
}];

becomes this structure

const arr = [{
 id:1,
 parentId:0,
 title: "1"
},{
 id:22,
 parentId:1,
 title: "1-1"
},{
 id:33,
 parentId:1,
 title: "1-2"
}{
 id:2,
 parentId:0,
 title: "2"
},{
 id:44,
 parentId:1,
 title: "2-1"
},{
 id:55,
 parentId:2,
 title: "2-2"
}];

what result do you expect? What is the error message actually seen?

Mar.04,2022

Recursive traversal is fine

function trans(data) {
    let transData = []

    function go(data) {
        for (let item of data) {
            let {
                parentId, title, id, children
            } = item;
            let newItem = {
                parentId, title, id
            }
            transData.push(newItem)
            if (children) {
                go(children)
            }
        }
    }
    go(data)
    return transData;
}
let newData = trans(treeNode)
console.log(newData)

var result = []
function flat(nodes, parentId) {
  if(!nodes || nodes.length === 0) return []
  nodes.forEach(node => {
    result.push({title: node.title, id: node.id, parentId: parentId})
    return flat(node.children, node.id)
  })
}

flat(treeNode, 0)

5743 has been answered perfectly, so make some modifications. Now that parentID, already exists, you don't need to give it to ID recursively, you just need to take it.

const opentree = tree => {
      let result = [];
      const flat = nodes => {
        if (nodes && nodes.length > 0)
          nodes.forEach(node => {
            result.push({ title: node.title, id: node.id, parentId: node.parentId });
            flat(node.children);
          });
      };
      flat(tree);
      return result;
    };
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3281d-2be37.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3281d-2be37.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?