const data = [
{
label: '接口描述',
key: '/api/address/finance',
usePage: false,
total: 0,
type: 'Object',
mixData: false,
range: [1, 10],
enum: [1,2,3],
props: [
{
label: '类型',
key: 'categrap',
type: 'Object',
range: '2,3',
enum: '4,5,6',
props: [
{
label: '金额',
key: 'money',
type: 'Number',
range: '10000, 100000'
},
{
label: '金额1',
key: 'money1',
type: 'Number',
range: '10000, 100000'
}
]
},
{
label: '类型1',
key: 'categrap1',
type: 'Object',
range: '2,3',
enum: '4,5,6',
props: [
{
label: '金额1',
key: 'money1',
type: 'Number',
range: '10000, 100000'
},
{
label: '金额2',
key: 'money2',
type: 'Number',
range: '10000, 100000'
}
]
}
]
}
]
function stringToArray(obj) {
if (obj.range) {
obj.range = obj.range.split(',')
}
if (obj.enum) {
obj.enum = obj.enum.split(',')
}
}
function tree2json(data) {
let jsonData = {}
data.forEach(item => {
const { props } = item
if (Array.isArray(props) && props.length > 0) {
const tempData = {}
item.props = tempData
props.forEach(prop => {
const clientKey = prop.key
delete prop.key
tempData[clientKey] = prop
if (
['Object', 'Array'].includes(prop.type)
&& Array.isArray(prop.props) && prop.props.length > 0
) {
tempData[clientKey].props = tree2json(prop.props)
}
stringToArray(prop)
})
jsonData = item
} else {
const clientKey = item.key
delete item.key
jsonData[clientKey] = item
stringToArray(item)
}
})
return jsonData
}
const treeData = JSON.parse(JSON.stringify(data))
const json = tree2json(treeData)
console.log(json)
function arrayToString(obj) {
if (Array.isArray(obj.range)) {
obj.range = obj.range.join(',')
}
if (Array.isArray(obj.enum)) {
obj.enum = obj.enum.join(',')
}
return obj
}
function json2tree(json, isRootNode = false) {
const list = []
let { props } = json
if (isRootNode) {
json.props = list
arrayToString(json)
} else {
props = json
}
for (const key in props) {
const tempData = {}
if (Object.hasOwnProperty.call(props, key)) {
const val = props[key];
if (val.props) {
val.props = json2tree(val.props)
}
arrayToString(val)
Object.assign(tempData, val, { key })
list.push(tempData)
}
}
return isRootNode ? [json] : list
}
const root = json2tree(json, true)
console.log(root)
console