How to convert JavaScript array into tree structure

How to convert JavaScript array into tree structure

1. Demand

The backend provides such data for the front end to convert into a tree structure (without duplicate data). Without further ado, let's first take a look at what kind of array data is given and what kind of tree structure it is converted into.

The array sent by the server

const arr = [
      [
        {"deptId":"D019",
        "deptName":"Sales Department"},
        {"deptId":"D019101",
        "deptName":"North China Sales Center"}
      ],[
        {"deptId":"D083",
        "deptName":"Music Department"}
      ],[
        {"deptId":"D027",
        "deptName":"Hangzhou Research Institute"},
        {"deptId":"D027048",
        "deptName":"Technical Engineering Division"},
        {"deptId":"D027048002",
        "deptName":"Project Management Center"}
      ],[
        {"deptId":"D027",
        "deptName":"Hangzhou Research Institute"},
        {"deptId":"D027048",
        "deptName":"Technical Engineering Division"}
      ],[
        {"deptId":"D027",
        "deptName":"Hangzhou Research Institute"},
        {"deptId":"D027048",
        "deptName":"Technical Engineering Division"}
      ]
    ]

Finally converted to

const arr = [
    {
      deptId: 'D019',
      deptName: 'Sales Department',
      children: [{
        deptId: 'D019101',
        deptName: 'North China Sales Center',
        children: [],
      }]
    },
    {
      deptId: 'D083',
      deptName: 'Music Department',
      children: []
    },
    {
      deptId: 'D027',
      deptName: 'Hangzhou Research Institute',
      children: [{
        deptId: 'D027048',
        deptName: 'Technical Engineering Division',
        children: [{
          deptId: 'D027048002',
          deptName: 'Project Management Center',
          children: []
        }]
      }]
    },
  ]

2. Code (developed in reactHooks)

const [treeData, setTreeData] = useState([]);
  console.log(treeData); //treeData is the final tree structure required (printed in my local browser is correct)
  
  useEffect(() => {
    : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : :
    const arr = JSON.parse(str).flat(); //Flattening let newArr = [];
    noRepeat(arr).length && noRepeat(arr).forEach(it => {
      appendChild(it, newArr);
    });
  }, [])

  const noRepeat = (arr) => { //Remove duplicates let newobj = {}; 
    return arr.reduce((preVal, curVal) => {
    newobj[curVal.deptId] ? '' : newobj[curVal.deptId] = preVal.push(curVal); 
      return preVal 
    }, []);
  }

  const appendChild = (item, newArr) => {
    if(!newArr.find(it => item.deptId.indexOf(it.deptId) > -1)) { //All first-level departments newArr.push({
        deptId: item.deptId,
        deptName: item.deptName,
        children: [],
      });
      setTreeData(newArr);
    }else {
      appendOtherChild(item, newArr);
    }
  }

  const appendOtherChild = (item, newArr) => {
    newArr.map(it => {
      if(item.deptId.indexOf(it.deptId) > -1 && item.deptId.length === it.deptId.length+3) {
        it.children.push({
          deptId: item.deptId,
          deptName: item.deptName,
          children: [],
        })
      }else {
        appendOtherChild(item, it.children);
      }
    });
    setTreeData(newArr);
  }

Summarize

Maybe these data are different from yours, but the logic is probably pretty close. You can take a good look at these dozens of lines of code.

This is the end of this article on how to convert JavaScript arrays into tree structures. For more information on converting JavaScript arrays into tree structures, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS uses the reduce() method to process tree structure data
  • A brief discussion on an efficient algorithm for constructing tree structures in JavaScript
  • JavaScript efficient algorithm for converting flat data into tree structure
  • How to use recursion to write a simple tree structure example in javascript
  • JSON complex data processing: converting Json tree structure data into Java objects and storing them in the database

<<:  Detailed installation and uninstallation tutorial for MySQL 8.0.12

>>:  When a Linux (Ubuntu) user enters an incorrect password N times in a row to log in, the system will be automatically locked for X minutes

Recommend

Use thead, tfoot, and tbody to create a table

Some people use these three tags in a perverted wa...

js method to delete a field in an object

This article mainly introduces the implementation...

Various ways to modify the background image color using CSS3

CSS3 can change the color of pictures. From now o...

Mysql implements three functions for field splicing

When exporting data to operations, it is inevitab...

Tutorial on processing static resources in Tomcat

Preface All requests in Tomcat are handled by Ser...

JS implements a stopwatch timer

This article example shares the specific code of ...

nginx solves the problem of slow image display and incomplete download

Written in front Recently, a reader told me that ...

TypeScript Enumeration Type

Table of contents 1. Overview 2. Digital Enumerat...

W3C Tutorial (2): W3C Programs

The W3C standardization process is divided into 7...

Linux kernel device driver address mapping notes

#include <asm/io.h> #define ioremap(cookie,...

Vue implements real-time refresh of the time display in the upper right corner

This article example shares the specific code of ...