Skip to content

Instantly share code, notes, and snippets.

@qzm
Last active December 4, 2018 03:12
Show Gist options
  • Save qzm/1d13e2e381908048c15887fd39ad2101 to your computer and use it in GitHub Desktop.
Save qzm/1d13e2e381908048c15887fd39ad2101 to your computer and use it in GitHub Desktop.
复制树形结构里面的key值(纯函数),保留原来的key值
/**
* 复制树形结构里面的key值(纯函数),保留原来的key值
*
* @export
* @param {Array} src 源
* @param {String} childrenIndex children 的 index
* @param {String} souceKey 原来的key
* @param {String} distKey 替换之后的key
* @returns
*/
export function copyKeyDeep(src, souceKey, distKey, childrenIndex = 'children') {
let sourceArray = src;
const isArray = Array.isArray(src);
if (!isArray) {
sourceArray = [src];
}
const result = sourceArray.map(item => {
if (Array.isArray(item[childrenIndex])) {
return {
...item,
[distKey]: item[souceKey],
[childrenIndex]: copyKeyDeep(item[childrenIndex], souceKey, distKey, childrenIndex),
};
}
return {
[distKey]: item[souceKey],
...item,
};
});
if (!isArray) {
return result[0];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment