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
198 views
in Technique[技术] by (71.8m points)

如何修改 JS Object 数据结构?

我有一组原始数据,结构为:

[{index: '1', title: '第1层'},
{index: '1-1', title: '第一层第1个'},
{index: '1-2', title: '第一层第2个'},
{index: '2', title: '第2层'}]

想要转换为一种嵌套结构:

[{index: '1', title: '第1层', children:[{index: '1-1', title: '第一层第1个'},{index: '1-2', title: '第一层第2个'}]},
{index: '2', title: '第2层'}]

我的能力有限,想了很久也没有办法尝试。只有一个浅浅的思路:

for (let i = 0; i < data.length; i++) {
    // 将 index 拆分为数组
    const pos = String(_data[i].index).split('-');
    
    // 得到数组结构,根据数组结构判断后追加 children
    // ...
}

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

1 Answer

0 votes
by (71.8m points)
var arr =[{index: '1', title: '第1层'},
{index: '1-1', title: '第一层第1个'},
{index: '1-2', title: '第一层第2个'},
{index: '2', title: '第2层'}];
var arr2=[];
arr.forEach((item,i)=>{
    // console.log(item.index.indexOf('-')!=-1)
    if(item.index.indexOf('-')!=-1){
            // console.log(item.index.split('-')[0])
            arr2.forEach((val,j)=>{
                if(!val.children){
                    val.children = [];
                }
                if(item.index.split('-')[0]==val.index){
                    console.log(val)
                    val.children.push(item)
                }
            })
    }else{
        arr2.push(item);
        // console.log(arr2)
    } 
})

补充:如果数据排序是乱的,需要处理一下

 var arr =[
        {index: '1-1', title: '第一层第1个'},
        {index: '1', title: '第1层'},
        {index: '2-2', title: '第2层第2个'},
        {index: '1-2', title: '第一层第2个'},
        {index: '2', title: '第2层'},
        {index: '2-1', title: '第2层第1个'},
        {index: '3-2', title: '第3层第2个'},
        {index: '3', title: '第3层'},
        {index: '3-1', title: '第3层第1个'},
        {index: '1-3', title: '第1层第3个'},
    ];
     
// 先过滤一下是父级的就是想要的结构
var arr1 = arr.filter((item) => {
    return item.index.indexOf('-') == -1
})

arr1.forEach((val)=>{
    val.children=[]; 
    arr.forEach((item) => {
    if (item.index.indexOf('-') != -1&&item.index.split('-')[0] == val.index) {
         val.children.push(item) 
        }
    }) 
})  

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

...