React-用行标题和列标题填充表的数据

时间:2018-11-17 16:37:16

标签: javascript reactjs ecmascript-6 html-table

我必须构建并填充具有行标题和列标题的表。 像这样:

<table>
  <tr>
    <th></th>
    <th scope="col">January</th>
    <th scope="col">February</th>
  </tr>
  <tr>
    <td>1</td>
    <td>$100</td>
    <td>$80</td>
  </tr>
  <tr>
    <td>2</td>
    <td>$90</td>
    <td>$80</td>
  </tr>
</table>

我从API获得的数据的格式为:

{
    item: '1',
    month: 'January',
    res:0,
    savings: 100
  },
  {
    item: '1',
    month: 'February',
    res: 0,
    savings: 80,
  },
  {
    item: '2',
    month: 'January',
    savings: 90,
  },
  {
    item: '2',
    month: 'February',
    res: 0
    savings: 80
  },

这是我尝试过的:

render() {
const contents = data[0].groupDetail.values.map(testData => {
      return <tr>
        <td>{testData.item}</td>
        <td>{testData.month}</td>
        <td>{testData.savings}</td>
      </tr>
    })
return(
<table>
              <tr>
                 <th></th>
        <th scope="col">January</th>
        <th scope="col">February</th>
              </tr>

                {contents}
</table>
)}

我不确定如何转换此数据以填充表。我尝试了.map,每个项目出现了两次。有人可以帮忙这里的方法吗?谢谢!

  

更新:这是我现在拥有的:

const grouped = _.groupBy(data[0].groupDetail.values, data => data.item);

let result = Object.keys(grouped).map(key => {
      return (
        <tr>
          <td>
            {key}
          </td>
          {Object.keys(grouped[key]).map(itemText => {
            return (
              <td>
                {grouped[key][itemText]['fieldName']}
              </td>
            )
          })}
        </tr>
      );
    });

1 个答案:

答案 0 :(得分:0)

这应该有效=)

const items = [{
    item: '1',
    month: 'January',
    savings: 100,
  },
  {
    item: '1',
    month: 'February',
    savings: 80,
  },
  {
    item: '2',
    month: 'January',
    savings: 90,
  },
  {
    item: '2',
    month: 'February',
    savings: 80,
  }
];

const groupBy = (objectArray, property) => {
  return objectArray.reduce(function(acc, obj) {
    const key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}

const groupedItems = groupBy(items, 'item');

  return (
    <table>
      <tr>
        <th></th>
        <th scope="col">January</th>
        <th scope="col">February</th>
      </tr>
      {Object.keys(groupedItems).map(item => (
          <tr>
            <td>{item}</td>
              {groupedItems[item].map(item => (
                <td>{item.savings}</td>
              ))}
          </tr>
      ))}
    </table>
  )