如何从数据对象中筛选指定key对应的值生成表格行?
解决方案
filter函数的作用是筛选数组中符合条件的元素,没法直接提取对象的指定属性,这就是你用它无效的原因。要实现需求,得用map遍历数据数组,对每个对象提取tableTh指定的key对应的值,具体实现如下:
示例代码(生成表格行数据)
// 手动设置的表头(目标key列表) const tableTh = ['name', 'age', 'email']; // 原始数据数组 const dataList = [ { id: 1, name: '张三', age: 25, email: 'zhangsan@example.com', address: '北京' }, { id: 2, name: '李四', age: 30, email: 'lisi@example.com', address: '上海' } ]; // 生成仅包含指定key的表格行数据 const tableRows = dataList.map(item => { // 对每个对象,按tableTh的key顺序提取对应值 return tableTh.map(key => item[key]); }); console.log(tableRows); // 输出结果: // [['张三', 25, 'zhangsan@example.com'], ['李四', 30, 'lisi@example.com']]
如果要生成DOM表格行元素
// 获取表格tbody容器 const tableBody = document.querySelector('table tbody'); dataList.forEach(item => { const row = document.createElement('tr'); // 遍历tableTh的key,生成每个单元格 tableTh.forEach(key => { const cell = document.createElement('td'); cell.textContent = item[key]; row.appendChild(cell); }); tableBody.appendChild(row); });
核心逻辑是:先用map/forEach遍历原始数据数组,再针对每个对象,根据tableTh的key列表提取对应属性值,最终组成表格需要的行数据或DOM元素。
内容的提问来源于stack exchange,提问作者Denis
相关产品推荐
相关产品推荐

