多级嵌套数组对象更改key-递归比JSON.stringfy操作字符快近20倍

在这里插入图片描述一直以为递归代码量多,操作字符代码量少,以为操作字符会更快,
故使用数据实际验证,递归更快
在这里插入图片描述

el-cascader层级数据,将后台字段key更改为label,value

在这里插入图片描述递归新增key: 时间在0.3~0.6ms之间

转字符串(JSON.parse(JSON.stringfy())):时间在10~20ms之间

在这里插入图片描述
方法一:递归更改或者新增key

// An highlighted block
console.log('%c 处理340条层级数据,2个方法耗费时间对比','color:red')

console.log('340条数据', val)
console.time()

function rewriteKey(val){
    val.forEach(item => {
      item.label = item.permissionName
      item.value = item.permissionId
      if(item.children){
        rewriteKey(item.children)
      }
    })
}
rewriteKey(val)

console.timeEnd()
console.log('%c 上面为递归方法耗时','color:#409EFF')
console.log('%c 转换后一条数据' + JSON.stringify(val[0]), 'color:#409EFF')

方法二:操作字符,将数组stringfy后,替换key,后转为数组

// An highlighted block
console.time()
let i = val && JSON.stringify(val).replace(/permissionName/g,'label2')
let i2 = i && i.replace(/permissionId/g, 'value2')
this.parentSelectArr = i2 && JSON.parse(i2)
console.timeEnd()
console.log('%c 上面为先将数组转为字符串,使用replace替换字段名,后转为数组方法耗时','color:#00965e')
console.log('%c 转换后一条数据' + JSON.stringify(this.parentSelectArr[0]), 'color:#00965e')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值