JavaScript实现按指定type属性筛选数组对象并渲染表格
实现Type筛选的下拉选择器与表格联动
嘿,这个需求挺常见的,我给你整理了一套清晰的实现方案,用原生JavaScript就能搞定,上手很简单:
第一步:搭建基础HTML结构
先把下拉筛选器和数据表格的骨架搭好:
<!-- 类型筛选下拉框 --> <select id="typeFilter"> <option value="all">全部类型</option> </select> <!-- 数据展示表格 --> <table id="dataTable" border="1"> <thead> <tr> <th>名称</th> <th>类型</th> </tr> </thead> <tbody> <!-- 数据行将在这里动态生成 --> </tbody> </table>
第二步:编写JavaScript逻辑
接下来处理数据提取、筛选和渲染的核心逻辑,每一步我都标了注释:
// 你的原始数据数组 const myArray = [ {name: "aaa", type: "1"}, {name: "bbb", type: "2"}, {name: "aaa", type: "3"}, {name: "ddd", type: "1"}, {name: "xxx", type: "3"}, {name: "bbbb", type: "1"} ]; // 获取页面上的DOM元素 const typeFilter = document.getElementById('typeFilter'); const tableBody = document.getElementById('dataTable').querySelector('tbody'); // 1. 提取所有不重复的type选项,添加到下拉框里 const uniqueTypes = [...new Set(myArray.map(item => item.type))]; uniqueTypes.forEach(type => { const option = document.createElement('option'); option.value = type; option.textContent = `类型${type}`; typeFilter.appendChild(option); }); // 2. 封装表格渲染函数,方便复用 function renderTable(filteredData) { // 先清空表格现有内容 tableBody.innerHTML = ''; // 遍历筛选后的数据,生成表格行 filteredData.forEach(item => { const row = document.createElement('tr'); row.innerHTML = ` <td>${item.name}</td> <td>${item.type}</td> `; tableBody.appendChild(row); }); } // 3. 页面加载完成后,先渲染所有数据 renderTable(myArray); // 4. 给下拉框添加筛选事件监听 typeFilter.addEventListener('change', function() { const selectedType = this.value; let filteredData; if (selectedType === 'all') { // 选"全部"时展示所有数据 filteredData = myArray; } else { // 筛选出匹配当前type的数据 filteredData = myArray.filter(item => item.type === selectedType); } // 重新渲染表格 renderTable(filteredData); });
核心逻辑说明
- 提取唯一Type:用
Set集合自动去重,再转成数组,确保下拉框不会出现重复的类型选项 - 复用渲染函数:把表格渲染逻辑封装成函数,不管是初始加载还是筛选后更新,都能直接调用,减少重复代码
- 实时筛选联动:监听下拉框的
change事件,根据选中的值动态筛选数据,再更新表格内容
这个方案很灵活,后续如果新增type或者修改数据结构,只需要调整少量代码就能适配~
内容的提问来源于stack exchange,提问作者Leo Messi
相关产品推荐
相关产品推荐

