Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

请教一个js数据格式装换问题

有没有比较好的方法吧图一的数据装换成图二的样子,规则是同名的key和value合并,组装成父子级的关系,而且leve可能有很多层可以嵌套很多层,请问下有比较好的方法吗?

图一图二


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

需要线确定树的层级机构,用levels表示,可以像下面这样处理,具体想要的数据结构看你需求再修改下

let levels = ['level1', 'level2', 'level3']
function arayToTree(arr, index){
    index = index || 0
    let result = [], obj = {}, props = levels[index]
    if(!props || index == levels.length - 1){
        return arr
    }
    arr.forEach(item => {
        if(obj[item[props]]){
            obj[item[props]].push(item)
        }else{
            obj[item[props]] = [item]
        }
    })
    
    for(let k in obj){
        result.push({
            name: k,
            child: arayToTree(obj[k], index + 1)
        })
    }
    
    return result
}

let arr = [
    {
        level1: 'a1',
        level2: 'b1',
        level3: 'c1',
        title: 'tt'
    },{
        level1: 'a1',
        level2: 'b1',
        level3: 'c2',
        title: 'tt'
    },{
        level1: 'a2',
        level2: 'b1',
        level3: 'c1',
        title: 'tt'
    },{
        level1: 'a2',
        level2: 'b2',
        level3: 'c1',
        title: 'tt'
    }
]

let data = arayToTree(arr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...