欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript樹(shù)型數(shù)據(jù)與一維數(shù)組相互轉(zhuǎn)換方式

 更新時(shí)間:2023年06月07日 11:09:21   作者:明天也要努力  
這篇文章主要介紹了JavaScript樹(shù)型數(shù)據(jù)與一維數(shù)組相互轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

JS樹(shù)型數(shù)據(jù)與一維數(shù)組相互轉(zhuǎn)換

1. 父子關(guān)系數(shù)據(jù)(一維數(shù)組)轉(zhuǎn)換為樹(shù)型結(jié)構(gòu)數(shù)據(jù)

1.1 原始數(shù)據(jù)

var source = [
	{
    id: 1,
    pid: 0,
    name: '江蘇省'
  },{
      id: 2,
      pid: 1,
      name: '南京市'
  },{
      id: 7,
      pid: 0,
      name: '上海市'
  }, {
    id: 3,
    pid: 2,
    name: '鼓樓區(qū)'
  },{
    id: 6,
    pid: 5,
    name: '武漢市' 	
  },{
    id: 4,
    pid: 2,
    name: '玄武區(qū)' 	
  },{
  	id: 5,
    pid: 0,
    name: '湖北省' 	
  }]

1.2 js代碼

function toTree(data) {
  	let result = [];
	if (!Array.isArray(data)) {
		return result;
	}
	data.forEach(item => {
		delete item.children;
	});
	let map = {};
	data.forEach(item => {
		map[item.id] = item; // id為鍵,原數(shù)據(jù)每一項(xiàng)為值的map對(duì)象
	});
	data.forEach(item => {
		let parent = map[item.pid]; // item的pid若與map對(duì)象的鍵相同,則item為父級(jí)節(jié)點(diǎn)
		let label = "";
		item.label = item.name;
		if (parent) {
		  (parent.children || (parent.children = [])).push(item);
		    parent.children.forEach(_item => {
		      _item.label = _item.name; 
		    });
		} else {
		  result.push(item);
		}
	});
	console.log(result)
	return result;
}
toTree(source);

1.3 轉(zhuǎn)換效果

2. 樹(shù)型結(jié)構(gòu)數(shù)據(jù)轉(zhuǎn)換為一維數(shù)組

2.1 原始數(shù)據(jù)

const treeObj = {
  id: '0',
  name: '中國(guó)',
  children:[
    {
      id: '1',
      name:'湖北省',
      children:[
        {
          id: '1-1',
          name:'武漢市',
          children:[
            {
              id: '1-1-1',
              name:'武昌區(qū)',
            },        
          ]
        },    
      ]
    },
    {
      id: '2',
      name:'江蘇省',
      children:[
        {
          id: '2-1',
          name:'南京市',
          children:[
            {
              id: '2-1-1',
              name:'玄武區(qū)',
            }   
          ]
        },    
        {
          id: '2-2',
          name:'鎮(zhèn)江市',
          children:[
            {
              id: '2-2-1',
              name:'句容市',
              children: [
                {
                  id: '2-2-1-1',
                  name:'下蜀鎮(zhèn)',
                },       
              ]
            },    
            {
              id: '2-2-2',
              name:'京口區(qū)'
            },    
          ]
        },       
      ]
    },
    {
      id: '3',
      name:'浙江省',
    }    
  ]
};

2.2 js代碼

// 將treeObj中的所有對(duì)象,放入一個(gè)數(shù)組中,要求某個(gè)對(duì)象在另一個(gè)對(duì)象的children時(shí),其parent_id是對(duì)應(yīng)的另一個(gè)對(duì)象的id
// 其原理實(shí)際上是數(shù)據(jù)結(jié)構(gòu)中的廣度優(yōu)先遍歷
function tree2Array(treeObj, rootid) {
   const temp = [];  // 設(shè)置臨時(shí)數(shù)組,用來(lái)存放隊(duì)列
   const out = [];    // 設(shè)置輸出數(shù)組,用來(lái)存放要輸出的一維數(shù)組
   temp.push(treeObj);
   // 首先把根元素存放入out中
   let pid = rootid;
   const obj = deepCopy(treeObj);
   obj.pid = pid;
   delete obj['children'];
   out.push(obj)
   // 對(duì)樹(shù)對(duì)象進(jìn)行廣度優(yōu)先的遍歷
   while(temp.length > 0) {
       const first = temp.shift();
       const children = first.children;
       if(children && children.length > 0) {
           pid = first.id;
           const len = first.children.length;
           for(let i=0;i<len;i++) {
               temp.push(children[i]);
               const obj = deepCopy(children[i]);
               obj.pid = pid;
               delete obj['children'];
               out.push(obj)
           }
       } 
   }
   return out
}
console.log(tree2Array(treeObj, 'root'))
// 深拷貝
function deepCopy(obj){
    // 深度復(fù)制數(shù)組
    if(Object.prototype.toString.call(obj) === "[object Array]"){    
      const object=[];
      for(let i=0;i<obj.length;i++){
        object.push(deepCopy(obj[i]))
      }   
      return object
    }
    // 深度復(fù)制對(duì)象
    if(Object.prototype.toString.call(obj) === "[object Object]"){   
      const object={};
      for(let p in obj){
        object[p]=obj[p]
      }   
      return object
    }
}

2.3 轉(zhuǎn)換效果

JS樹(shù)結(jié)構(gòu)轉(zhuǎn)換為一維數(shù)組,tree轉(zhuǎn)list

let treeData = [{ "pid": null, "id": 2 }, { "pid": null, "id": 3, "children": [{ "pid": 3, "id": 4, "children": [{ "pid": 4, "id": 6, "children": [{ "pid": 6, "id": 5 }] }] }] }]
    function fn(arr) {
        let data = JSON.parse(JSON.stringify(arr))
        let newData = []
        const callback = (item) => {
            (item.children || (item.children = [])).map(v => {
                callback(v)
            })
            delete item.children
            newData.push(item)
        }
        data.map(v => callback(v))
        return newData
    }
    console.log(toTree(fn(treeData)), '===')

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論