前端开发返回请求数据后重组数据结构的常见几种模式与解决方案

前端重组数据结构的常见几种模式与解决方案

数据格式一:

list = [{id: '01', name: '01',parent: null},
        {id: '0101',name: '0101',parent: '01'},
        {id: '010101',name: '010101',parent: '0101'},
        {id: '0102',name: '01012',parent: '01'},
        {id: '012',name: '012',parent: null},
        {id: '0201',name: '0201',parent: '02'},
      ]

需求数组重组后输出的格式如下:

[{id::'',name:'',parent:'',children:[{id::'',name:'',parent:'',children:[{...}]}...]}]

解决方案与思路
循环递归判断

处理方式代码

  const makeList = (list, parent) => {
            let _new = list.filter(val => val.parent === parent)
            // 排序
            _new.sort((a, b) => b.name - a.name)
            // 重组数据结构
            for (let item of _new) {
                let hasChild = list.findIndex(oo => oo.parent === item.id)
                if (hasChild > -1)
                    item.children = makeList(list, item.id)
            }
            return _new
        }
        let newList = makeList(list, null)
        console.log(newList)

数据格式二

const list = [
{ id:'01', name:'01',children:[{id:'0101',name:'0101',children:[{id:'010101',name:'010101'}]}] },
{ id:'02', name:'02',children:[{id:'0202',name:'0202',children:[{id:'020202',name:'020202'}]}] },
.................
]

需求如下:
对于这种数据结构,需要层次递进查找一个元素,或者修改其中一个元素
解决方案

    const getItem = (key: string, data: {}[]) => {
        data.forEach((it: any) => {
            if (it.key === key) {
                item = it
                return
            }
            else if (it.children) {
                getItem(key, it.children)
            }
        })
        return item
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值