如何修改 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
    // ...
}
阅读 2.3k
2 个回答
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) 
        }
    }) 
})  
var a =[
        {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 result = Object.values(a.reduce((r, item) => {
    const { index } = item;
    const [ parentIndex, childIndex] = index.split('-');
    
    if(childIndex == null) {
        r[parentIndex] = Object.assign({}, r[parentIndex], item);
    } else {
        r[parentIndex] = r[parentIndex] || {};
        r[parentIndex].children = r[parentIndex].children || [];
        r[parentIndex].children.push(item);
    }

    return r;
}, {}))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题