有时候,咱们须要将后台传回的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文件函数