有時候,咱們須要將後臺傳回的JOSN格式展現給用戶看,這時須要將json格式的數據轉爲樹結構所須要的數據結構,如圖:react
其須要轉換的數據結構:json
[{
"key": key,
"title": title,
"children": [{
"key": key,
"title": title,
"children": [{
"key": subKey,
"title": subTitle,
}]
}]
}]複製代碼
思路:數組
一、首選須要一個函數來判斷 value 值的數據類型,若是不是對象,則說明其是沒有子元素的,若是是對象,則須要添加key值children繼續展現其子元素bash
// 數據類型
checkDataType(data) {
let type = null
if (typeof data === 'object') {
// 對象
if (Object.prototype.toString.call(data) === "[object Null]") {
// null
type = 'null'
} else if (Object.prototype.toString.call(data) === "[object Array]") {
// []
type = 'array'
} else if (Object.prototype.toString.call(data) === "[object Object]") {
// {}
type = 'object'
}
} else {
// 除 null 的基本數據類型
type = 'common'
}
return type
}
複製代碼
二、其次即是轉換成咱們想要的數據結構,主要有兩點:一個是須要一個數組來存儲遍歷的key值,經過這個數組才能在對應的key值下面添加children或者不添加;第二個充分利用對象的特性:名存在於棧內存中,值存在於堆內存中,可是棧內存會提供一個引用的地址指向堆內存中的值數據結構
verfiedData(data, _prekey, _tns) {
const tns = _tns || showData
// 判斷子元素的數據類型
let dataType = this.checkDataType(data)
switch (dataType) {
case 'object':
const children = []
// 記錄key值,目的爲了尋找對應的插入位置
for (let i in data) {
const key = i
if (this.checkDataType(data[i]) === 'common' || this.checkDataType(data[i]) === 'null') {
tns.push({
title: `${key}: ${data[i]}`,
key: key
})
// 若是沒有子元素了,必定要插入一個佔位符,否則會錯位
children.push('noChild')
} else {
tns.push({
title: key,
key
})
children.push(key)
}
}
children.forEach((key, index) => {
//尋找對應的插入位置,若沒有子元素了,直接返回,若是有,插入key值爲children的數組,再次調用函數
if (key === 'noChild') {
return tns
} else {
tns[index].children = []
this.verfiedData(data[key], key, tns[index].children)
}
})
break;
case 'array':
// 數組如下標做爲key
data.forEach((value, index) => {
tns.push({
title: index,
key: index
})
tns[index].children = []
this.verfiedData(data[index], index, tns[index].children)
});
break;
default:
tns.push({
title: data,
key: _prekey
})
}
}
複製代碼
三、調用app
this.verfiedData(certData)複製代碼
四、demo代碼地址:https://coding.net/u/sunqun/p/react-demo-app , containers目錄下Tree文件函數