应用场景
做树形数据时会有需要处理进行扁平化的操作来拿到里面的每一个孩子的id值,又要保留原有的树去做渲染,利用深拷贝+递归方法完成,直接上代码
const arr1=deepClone(arr)
moveChildrenLevel(arr)
/**
* 树形扁平化
* @param arr
* @returns {*}
*/
moveChildrenLevel(arr1) {
const send = []
const move = arr2 => {
arr2.forEach(item => {
send.push(item)
if (item.children) {
const children = Object.assign([], item.children)
delete item.children
move(children)
}
})
}
move(arr1)
return send
},
/**
* 深拷贝
* @param source
* @returns {*}
*/
util.deepClone = (source) => {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'shallowClone');
}
const targetObj = source.constructor === Array ? [] : {};
for (const keys in source) {
if (source.hasOwnProperty(keys)) {
if (source[keys] && typeof source[keys] === 'object') {
targetObj[keys] = source[keys].constructor === Array ? [] : {};
targetObj[keys] = util.deepClone(source[keys]);
} else {
targetObj[keys] = source[keys];
}
}
}
return targetObj;
};