const arr = [
{
"title": 'aaaaa',
"href": '#ffasss',
"level": "1"
},
{
"title": "Getting Started",
"href": "#getting-started",
"level": "2"
},
{
"title": "Documentawqtion",
"href": "#docum2323entation",
"level": "4"
},
{
"title": "Documentwwation",
"href": "#documentwwwation",
"level": "5"
},
{
"title": "Documentatrqion",
"href": "#documentation",
"level": "6"
},
{
"title": "Installation",
"href": "#installation",
"level": "3"
},
{
"title": "API",
"href": "#api",
"level": "4"
},
{
"title": "I18n",
"href": "#i18n",
"level": "3"
},
{
"title": "Plugin",
"href": "#plugin",
"level": "3"
},
{
"title": "Sponsors",
"href": "#sponsors",
"level": "2"
},
{
"title": "Contributors",
"href": "#contributors",
"level": "2"
},
{
"title": "License",
"href": "#license",
"level": "2"
},
{
"title": "License",
"href": "#contributorsLicense",
"level": "1"
}
]
const newArr = []
const maps = []
const mark = {
curDeep: 0,
targetDeep: null,
parentObj: null,
}
function recursive(arr, raw, positive = true) {
if (!Array.isArray(arr) || !raw) return
const { parentObj, curDeep, targetDeep } = mark
if (targetDeep) {
if (curDeep !== targetDeep) {
const lastObj = arr[arr.length - 1]
mark.parentObj = lastObj
mark.curDeep++
return recursive(lastObj.children, raw)
} else {
mark.targetDeep = null
return recursive(arr, raw)
}
} else {
const childObj = Object.assign({ children: [] }, raw)
const isFindMap = maps.find(map => map.k === childObj.href)
const mapItem = isFindMap || { k: childObj.href, l: childObj.level, d: curDeep }
!isFindMap && maps.push(mapItem)
if (arr.length) {
if (childObj.level > parentObj.level) {
parentObj.children.push(childObj)
mark.curDeep++
mark.parentObj = childObj
mapItem.d = mark.curDeep
} else if (childObj.level < parentObj.level) {
const p = maps.reverse().find(item => item.l < childObj.level)
maps.reverse()
if (p) {
mark.targetDeep = p.d
mark.curDeep = 0
return recursive(arr, childObj)
} else {
arr.push(childObj)
}
} else {
mark.targetDeep = curDeep - 1
mark.curDeep = 0
return recursive(arr, raw)
}
} else {
arr.push(childObj)
mark.curDeep++
mark.parentObj = childObj
mapItem.d = mark.curDeep
}
}
}
forEachArr(arr)
function forEachArr(arr) {
if (!Array.isArray(arr) || !arr.length) return
arr.forEach((item, i) => {
recursive(newArr, item, true)
})
}
console.log('>>>>>>>>>>>', newArr, maps, mark)
console.log(arr.length)
console