今天做项目,碰到一个树形结构要给每一层重新添加一些属性,记录一下
const arr =[{
id: null,
code: '640200000',
children: [{
id: 15,
children:null
}]
}]
我需要每层都有一个不一样的key值,这个树形数据的首层id为null,不能做key值,然后利用lodash的 _.uniqueId 函数生成唯一ID。
const getNewData = arr => arr.map(item => ({
...item,
key: _.uniqueId('zstdTree_'),
children: getNewData(item.children || [])
}));
一开始遍历没有给children做空值兼容,报了Cannot read property ‘map’ of null 的错误,然后百度了下,参考链接
树形结构遍历:
https://segmentfault.com/q/1010000015775141
空值兼容:
https://blog.csdn.net/qq_36658051/article/details/90264899.