MappedTable
从对象数组中过滤指定的属性行,以动态表单形式渲染成表格
技能
- 使用
Object.keys(),Array.prototype.filter(),Array.prototype.includes()
和Array.prototype.reduce()
,得到过滤 后的filteredData
阵列,过滤数据包含具有规定key
的所有对象propertyNames
。 <table>
使用一组等于值的列来渲染元素propertyNames
。- 用于
Array.prototype.map
将propertyNames
数组中的每个值呈现为<th>
元素。 - 用于
Array.prototype.map
将filteredData
数组中的每个对象呈现为<tr>
元素,包含对象中的<td>
每个键。
function MappedTable({ data, propertyNames }) {
let filteredData = data.map(v =>
Object.keys(v)
.filter(k => propertyNames.includes(k))
.reduce((acc, key) => ((acc[key] = v[key]), acc), {})
);
return (
<table>
<thead>
<tr>
{propertyNames.map(val => (
<th key={`h_${val}`}>{val}</th>
))}
</tr>
</thead>
<tbody>
{filteredData.map((val, i) => (
<tr key={`i_${i}`}>
{propertyNames.map(p => (
<td key={`i_${i}_${p}`}>{val[p]}</td>
))}
</tr>
))}
</tbody>
</table>
);
}
其它
- 该组件不适用于嵌套对象,如果在
propertyNames
用法
const people = [
{ name: 'John', surname: 'Smith', age: 42 },
{ name: 'Adam', surname: 'Smith', gender: 'male' }
];
const propertyNames = ['name', 'surname', 'age'];
ReactDOM.render(
<MappedTable data={people} propertyNames={propertyNames} />,
document.getElementById('root')
);
效果
name | surname | age |
---|---|---|
John | Smith | 42 |
Adam | Smith |
来源
本作品采用《CC 协议》,转载必须注明作者和本文链接