{
value: 'q',
children: [
{
value: 'w',
children: [{ value: 'e' }, { value: 'r' }]
},
{
value: 't',
children: [{ value: '' }, { value: 'y' }, { value: 'u' }]
},
{ value: 'i' }
]
},
{
value: 'o'
}
];
const targetMap = new Map([
['q/w/e', undefined],
['q/t', undefined]
]);
function formatArr(arr, path) {
for (let idx = arr.length - 1; idx >= 0; idx--) {
const i = arr[idx];
let mapKey = arr[idx].value;
if (path) mapKey = `${path}${mapKey ? '/' : ''}${mapKey}`;
let flag = true;
let finish = false;
targetMap.forEach((value, key) => {
if (key === mapKey) {
finish = true;
} else {
const index = key.indexOf(mapKey);
if (flag && index === 0) flag = false;
}
});
if (finish) continue;
if (flag) {
arr.splice(idx, 1);
continue;
}
if (i.children) formatArr(i.children, mapKey);
}
}
const copyArr = JSON.parse(JSON.stringify(originArr));
formatArr(copyArr);
console.log(originArr, copyArr);
作用是根据一个 map 对象去找一个数组里面嵌套的值,表达可能不太清楚,代码能直接跑起来,输出一眼能看出来是干嘛的。求助大佬们这段代码怎么优化?感觉有很大的优化空间