JS recursive function with nested children array

Max*_*ich 0 javascript arrays object

i have tree array of nested objects. Depending on the type of element I want to give it the necessary icon.

const treeData = [
 {
  id: 1,
  type: "FOLDER",
  children: [
              {
                id: 2,
                type: "FILE"
              },
              {
                id: 2,
                type: "FOLDER",
                children: []
              },
            ]
 }
]
Run Code Online (Sandbox Code Playgroud)

Unlimited number of nesting possible in folders. Output should be like that.

const treeData = [
 {
  id: 1,
  type: "FOLDER",
  icon: "folder-icon"
  children: [
              {
                id: 2,
                type: "FILE",
                icon: "file-icon"
              },
              {
                id: 2,
                type: "FOLDER",
                children: []
                icon: "file-icon"
              },
            ]
 }
]
Run Code Online (Sandbox Code Playgroud)

As i understand i should use recursive map function with CHILDREN check. But i can't reach the proper result.

Nen*_*car 5

您可以使用map方法并创建一个递归函数,该函数将采用类型并将其转换为小写以创建图标名称并将其添加到新对象中。

const data = [{"id":1,"type":"FOLDER","children":[{"id":2,"type":"FILE"},{"id":2,"type":"FOLDER","children":[]}]}]

function addIcons(data) {
  return data.map(({ type, children = [], ...rest }) => {
    const o = { ...rest, type }
    if(type) o.icon = `${type.toLowerCase()}-icon`;
    if (children.length)  o.children = addIcons(children)
    return o
  })
}

console.log(addIcons(data))
Run Code Online (Sandbox Code Playgroud)