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

How to quickly deploy Redis as a Docker container

Table of contents getting Started Data storage Co...

Native JS realizes uniform motion of various sports

This article shares with you a uniform motion imp...

Example method of deploying react project on nginx

Test project: react-demo Clone your react-demo pr...

MySQL compressed package version zip installation configuration method

There are some problems with the compressed versi...

Detailed explanation of JS variable storage deep copy and shallow copy

Table of contents Variable type and storage space...

Detailed explanation of chmod command usage in Linux

chmod Command Syntax This is the correct syntax w...

How to implement html input drop-down menu

Copy code The code is as follows: <html> &l...

How to enhance Linux and Unix server security

Network security is a very important topic, and t...

Use html-webpack-plugin' to generate HTML page plugin in memory

When we package the webpackjs file, we introduce ...

Vue.js manages the encapsulation of background table components

Table of contents Problem Analysis Why encapsulat...

How to implement Ajax concurrent request control based on JS

Table of contents Preface Ajax serial and paralle...

Detailed example of changing Linux account password

Change personal account password If ordinary user...

Discuss the application of mixin in Vue

Mixins provide a very flexible way to distribute ...