JS实现单输入框对嵌套数组按profile_id等多字段过滤
嵌套数组多字段过滤实现方案
HTML结构
先搭建输入框和结果展示区域,输入内容时实时触发过滤:
<input type="text" id="filterInput" placeholder="输入关键词过滤(profile_id/nickname_id/nickname_value)"> <div id="result"></div>
JavaScript逻辑
核心是同时处理外层profile_id和内层nicknames的多字段匹配,完整实现代码如下:
// 原始数据集 const profiles = [ { "profile_id": 1, "nicknames": [ { "nickname_id": 230, "nickname_value": "Rob", "admin_id": 5, "created_at": "2023-01-08T13:20:24.000000Z", "updated_at": "2023-01-08T13:20:24.000000Z" }, { "nickname_id": 231, "nickname_value": "Wel", "admin_id": 5, "created_at": "2023-01-08T13:20:32.000000Z", "updated_at": "2023-01-08T13:20:32.000000Z" } ] }, { "profile_id": 12, "nicknames": [ { "nickname_id": 232, "nickname_value": "Pol", "admin_id": 5, "created_at": "2023-01-08T14:06:14.000000Z", "updated_at": "2023-01-08T14:06:14.000000Z" } ] } ]; // 获取DOM元素 const filterInput = document.getElementById('filterInput'); const resultDiv = document.getElementById('result'); // 核心过滤函数 function filterProfiles(keyword) { const lowerKeyword = keyword.toLowerCase().trim(); // 关键词为空时返回原始数据 if (!lowerKeyword) return [...profiles]; return profiles.reduce((filteredList, currentProfile) => { // 检查当前profile的id是否匹配关键词 const isProfileMatch = currentProfile.profile_id.toString().includes(lowerKeyword); // 过滤内层nicknames中符合条件的项 const matchedNicknames = currentProfile.nicknames.filter(nickname => { const isNicknameIdMatch = nickname.nickname_id.toString().includes(lowerKeyword); const isNicknameValueMatch = nickname.nickname_value.toLowerCase().includes(lowerKeyword); return isNicknameIdMatch || isNicknameValueMatch; }); // 只要profile自身匹配,或者有匹配的昵称项,就保留该profile if (isProfileMatch || matchedNicknames.length > 0) { filteredList.push({ ...currentProfile, nicknames: matchedNicknames // 替换为过滤后的昵称数组 }); } return filteredList; }, []); } // 渲染过滤结果到页面 function renderResults(data) { resultDiv.innerHTML = JSON.stringify(data, null, 2); } // 监听输入框变化,实时过滤 filterInput.addEventListener('input', (e) => { const filteredData = filterProfiles(e.target.value); renderResults(filteredData); }); // 页面加载时先渲染原始数据 renderResults(profiles);
关键逻辑说明
- 多字段兼容:把数字类型的
profile_id和nickname_id转成字符串再匹配,避免数字匹配的局限性;nickname_value转小写实现不区分大小写的模糊匹配 - 层级过滤:先过滤内层昵称数组,再判断外层profile是否需要保留——要么自身id匹配,要么有符合条件的昵称项
- 空值处理:如果关键词为空,直接返回原始数据;过滤后不会保留没有匹配项的profile对象
内容的提问来源于stack exchange,提问作者Arczi
相关产品推荐
相关产品推荐

