每天一点前端知识 - 数据过滤

共 2610字,需浏览 6分钟

 ·

2023-08-24 04:49

实现

    const filter = (list, keyword, fields = [], exact = false, str2Dom = null) => {
if (!isValidArr(list)) {
return [];
}
if (!keyword) {
return list;
}
fields = typeof fields === 'string' ? fields.split(',') : fields;
return list.filter(v => {
fields = fields.length > 0 ? fields : Object.keys(v);
const matched = fields.filter(field => {
const fieldValue = v[field];
if (fieldValue == null) {
return false;
}
if (exact) {
return fieldValue === keyword;
}
const reg = new RegExp(keyword, 'gi');
const match = fieldValue.toString().match(reg);
// 高亮
if (match && str2Dom) {
v[field] = str2Dom(fieldValue.toString().replace(reg, `<span style="background-color:yellow">${match[0]}</span>`), {display: 'inline-block'});
}
return match;
});
return matched.length;
});
};


const getMatched = fn =>
(arr, childKey = 'children') => {
if (!Array.isArray(arr)) {
return arr;
}
const list = clone(arr);
const traver = data => {
const matchedData = [];
data.map(v => {
if (isValidArr(v[childKey])) {
const matchChildren = traver(v[childKey]) || [];
v[childKey] = matchChildren;
if (matchChildren.length > 0) {
matchedData.push(v);
}
}
});
return fn(data, matchedData);
};
return traver(list);
};
const filterList = (data, keyword, fields = 'name', exact = false, idKey = 'id', childKey = 'children', str2Dom) => getMatched((list, matchedItem) => unique([...filter(list, keyword, fields, exact, str2Dom), ...matchedItem], idKey))(data, childKey);

使用

    filterList(data, keyword, fields = 'name', exact = false, idKey = 'id', childKey = 'children', null);

- data:列表数据
- keyword:搜索值
- fields:搜索字段,字符串或数组。根据属性过滤,默认 `name`,设为 `null` 则全局所有属性搜索
- exact:是否为精确匹配,默认是模糊搜索
- idKey:节点唯一标识符
- childKey:子节点属性值
- str2Dom:高亮关键词

示例

    const data = [
{
path: "/a",
name: "a",
parentId: "",
children: [
{ path: "/a/1", name: "a1", parentId: "/a", children: [] },
{ path: "/a/3", name: "a3", parentId: "/a", children: [] },
{ path: "/a/2", name: "a2", parentId: "/a", children: [] },
],
},
{
path: "/c",
name: "c",
parentId: "",
children: [
{ path: "/c/1", name: "c1", parentId: "/c", children: [] },
{ path: "/c/2", name: "c2", parentId: "/c", children: [] },
],
},
{
path: "/b",
name: "b",
parentId: "",
children: [
{
path: "/b/1",
name: "b1",
parentId: "/b",
children: [
{ path: "/b/1/1", name: "b11", parentId: "/b/1", children: [] },
],
},
{ path: "/b/2", name: "b2", parentId: "/b", children: [] },
],
},
];

filterList(data, '/1', 'path', false, 'path');

be7a9c0cea4f29344a2bcd2f5150b054.webp

1bd97af42ee0eb74dc9b00df234f7712.webp

高亮关键词:

71dc92a1f55d3cf0a1992b5955fa248d.webp

演示地址:https://ihuxy.com/play?utils=filterList


浏览 18
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报