2019-08-29
描述
使用对象数组和属性名称列表渲染一个动态创建行的表格。
- 使用 
Object.keys(),Array.prototype.filter(),Array.prototype.includes()和Array.prototype.reduce()得到一个filteredData数组,使其数组中的每一个对象中都包含propertyNames中所指定的 key 值 - 渲染一个 
<table>元素,表头<th>对应propertyNames中的每一个值 - 使用 
Array.prototype.map渲染propertyNames数组中的每一个值作为<th>元素 - 使用 
Array.prototype.map渲染filteredData数组中的每一个对象为一个<tr>元素,对象中的每一个 key 对应一个<td> 
该组建不能用于嵌套对象,如果 propertyNames 中指定的任何属性中存在嵌套对象,那么该组件将会进行中断
实现
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>
  );
}
使用
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')
);
        
                
                ME!
            
                
                链滴