js recursive cycle tree structure, according to a certain node value, add different state values to the object before the node, the current node, and the object after the node

Preface: Currently there is a process node data, multi-level tree structure. One of the nodes has a parameter isCurrent. When isCurrent is 1, it means the current process. When isCurrent is 0, it is submitted or unsubmitted. The process before isCurrent: 1 has been submitted, and the process after isCurrent: 1 has not been submitted. Currently, submitted and unsubmitted, three colors need to be displayed. Now add three different states for the current process, submitted, and uncommitted objects according to isCurrent: 1.

code show as below

//数据结构
  const obj = {
    
    
      name: '流程1',
      isCurrent: 0,
      childNode: {
    
    
        name: '流程2',
        isCurrent: 1,
        childNode: {
    
    
          name: '流程3',
          isCurrent: 0,
          childNode: {
    
    
            name: '流程4',
            isCurrent: 0
          }
        }
      }
    }

//数据处理
   const handleData = (node, type) => {
    
    
      for (const key in node) {
    
    
//首先找到isCurrent 1 当前环节,当前环节后面的childNode就是未流转的
        if (node.isCurrent == 1) {
    
    
          node.colorType = 2 //当前环节颜色
          if (node.childNode) {
    
    
            // 添加参数true代表这是未流转的childNode
            handleData(node.childNode, true)
          }
        }

        if (node.isCurrent == 0 && !type) {
    
    
          node.colorType = 1//已流转颜色
          if (node.childNode) {
    
    
            handleData(node.childNode, false)
          }
        }
        if (node.isCurrent == 0 && type) {
    
    
          node.colorType = 0 //未流转环节颜色
          if (node.childNode) {
    
    
            handleData(node.childNode, true)
          }
        }
      }
      return node
    }
//调用打印,首次调用,type为false
 console.log(handleData(obj))
 //数据如下
{
    
    
      'name': '流程1',
      'isCurrent': 0,
      'colorType': 1,
      'childNode': {
    
    
        'name': '流程2',
        'isCurrent': 1,
        'colorType': 2,
        'childNode': {
    
    
          'name': '流程3',
          'isCurrent': 0,
          'colorType': 0,
          'childNode': {
    
    
            'name': '流程4',
            'isCurrent': 0,
            'colorType': 0
          }
        }
      }
    }

The renderings are as follows

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43485503/article/details/129164743