React:映射和渲染分组行的表

时间:2017-11-09 22:42:47

标签: javascript arrays reactjs

我正在尝试将以下数据映射并呈现为一系列分组表,但我正在努力。任何人都可以指出我正确的方向......

数据

    [{
    group: "twitter",
    records : [
    {_id: "aMzJECeyvoLGdNzRM", 
    owner: "K7xTxu7PRDCuhFZRC", 
    company_ID: "1", 
    coreURL: "http://test88.com", 
    feedback: "Charles"
    },{
    _id: "aMzJECeyvoLGdNzRM", 
    owner: "K7xTxu7PRDCuhFZRC", 
    company_ID: "1", 
    coreURL: "http://test99.com", 
    feedback: "Gerry"
    }
    ]},{
    group: "linkedin",
    records : [
    {_id: "aMzJECeyvoLGdNzRM", 
    owner: "K7xTxu7PRDCuhFZRC", 
    company_ID: "1", 
    coreURL: "http://test88.com", 
    feedback: "Charles"
    },{
    _id: "aMzJECeyvoLGdNzRM", 
    owner: "K7xTxu7PRDCuhFZRC", 
    company_ID: "1", 
    coreURL: "http://test99.com", 
    feedback: "Gerry"
   }
   ]}]

我正在努力实现......

    *Group 1*
    - Item 1
    - Item 2

    *Group 2*
    - Item 1
    - Item 2

我已经能够将标准数据集映射并渲染到单个表中,但是却对分组元素进行了挣扎

2 个答案:

答案 0 :(得分:0)

您可以使用reduce function创建groupBy util并将其链接到Array原型。



Array.prototype.groupBy = function(key) {
  return this.reduce(function(groups, item) {
    const val = item[key];
    groups[val] = groups[val] || [];
    groups[val].push(item);
    return groups;
  }, {});
};

const data = [{
  group: "twitter",
  records: [{
    _id: "aMzJECeyvoLGdNzRM",
    owner: "K7xTxu7PRDCuhFZRC",
    company_ID: "1",
    coreURL: "http://test88.com",
    feedback: "Charles"
  }, {
    _id: "aMzJECeyvoLGdNzRM",
    owner: "K7xTxu7PRDCuhFZRC",
    company_ID: "1",
    coreURL: "http://test99.com",
    feedback: "Gerry"
  }]
}, {
  group: "linkedin",
  records: [{
    _id: "aMzJECeyvoLGdNzRM",
    owner: "K7xTxu7PRDCuhFZRC",
    company_ID: "1",
    coreURL: "http://test88.com",
    feedback: "Charles"
  }, {
    _id: "aMzJECeyvoLGdNzRM",
    owner: "K7xTxu7PRDCuhFZRC",
    company_ID: "1",
    coreURL: "http://test99.com",
    feedback: "Gerry"
  }]
}]

const groupedData = data.groupBy('group');
console.log(groupedData);




有些图书馆已经实施了这类方法,例如lodashunderscore

答案 1 :(得分:0)

我设法用以下内容对此进行排序,并在RecordListDetail组件中渲染分组表的每一行:

groupedTables(){
return groupedData.map ((group, index) => {
  return (
    <div key={index}>
    <div>
      {group.group}
    </div>
    <Table striped bordered condensed hover>
      <tbody>
        {group.records.map ((details, index) =>
        <RecordListDetail
          key={index}
          details={details}
        />
        )}
      </tbody>
    </Table>
  </div>