js常用工具函数
数组转树结构
递归
function dataToTree(list, parentId = 0) {
return list
.filter(item => item.cateParentId === parentId)
.map(item => ({
...item,
children: dataToTree(list, item.storeCateId)
}));
}Map+循环
push的是对象的引用,所以是能够实现多层级的
function dataToTree(list) {
const map = new Map();
const roots = [];
list.forEach(item => {
map.set(item.storeCateId, { ...item, children: [] });
});
list.forEach(item => {
const node = map.get(item.storeCateId);
if (item.cateParentId && map.has(item.cateParentId)) {
map.get(item.cateParentId).children.push(node);
} else {
roots.push(node);
}
});
return roots;
}树结构扁平化
递归处理
function treeToList(tree) {
const result = [];
const traverse = (nodes) => {
for (const node of nodes) {
const { children, ...rest } = node;
result.push(rest);
if (children && children.length) {
traverse(children);
}
}
};
traverse(tree);
return result;
}迭代 + 栈实现
function treeToList(tree) {
const stack = [...tree];
const result = [];
while (stack.length) {
const node = stack.pop();
const { children, ...rest } = node;
result.push(rest);
if (children && children.length) {
stack.push(...children);
}
}
return result;
}
数组去重by key
function uniqueByKey(arr, key) {
const map = new Map();
arr.forEach(item => {
if (!map.has(item[key])) {
map.set(item[key], item);
}
});
return Array.from(map.values());
}树结构字段映射
cateName,cateId,goodsCateList 映射为 label,value,children
function transformCateTree(list = []) {
return list.map(item => ({
label: item.cateName,
value: item.cateId,
children: item.goodsCateList && item.goodsCateList.length
? transformCateTree(item.goodsCateList)
: []
}))
}防抖
// 简单版防抖:只保留核心的延迟+重置逻辑
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
clearTimeout(timer); // 每次触发清空定时器,重置延迟
timer = setTimeout(() => {
fn.apply(this, args); // 延迟执行目标函数
}, delay);
};
}节流
// 简单版节流:时间戳实现,首次触发立即执行,间隔内不重复执行
function throttle(fn, interval = 300) {
let lastTime = 0; // 记录上一次执行时间
return function (...args) {
const now = Date.now();
// 只有当前时间 - 上次执行时间 > 间隔,才执行
if (now - lastTime > interval) {
fn.apply(this, args);
lastTime = now; // 更新上次执行时间
}
};
}
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果