react antd Table dynamically merge cells

Posted by Alidad on Wed, 27 Nov 2019 15:56:21 +0100

@TOC

Example data

Primitive array

const data = [
  {
    key: '0',
    name: 'John Brown',
    age:22,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '1',
    name: 'John Brown',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: '2',
    name: 'John Brown',
    age:22,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '5',
    name: 'Joe Black',
    age: 3,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
  {
    key: '6',
    name: 'Joe Black',
    age: 342,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
  {
    key: '7',
    name: 'Joe Black',
    age: 62,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];

The raw data is shown in Table as follows

name is the field to be merged in this example

The data fields include fake data such as key`nameageaddress`tags. The purpose is to merge elements with the same name into an array, and then expand these arrays into a new array that meets the antd Table rendering conditions, as follows:

The consolidated results are as follows

Merge cell solution

Merging function

//Merge array cells
  createNewArr=(data)=>{
    return data.reduce((result, item) => {
    //First, take the name field as a new array result
        if (result.indexOf(item.name) < 0) {
            result.push(item.name)
        }
        return result
    }, []).reduce((result, name) => {
    //Take the data with the same name as a new array, and add a new field * * rowSpan inside it**
      const children = data.filter(item => item.name === name);
      result = result.concat(
        children.map((item, index) => ({
          ...item,
          rowSpan: index === 0 ? children.length : 0,//Add the first row of data to the rowSpan field
        }))
      )
      return result;
    }, [])
  }

Usage method

const columns = [
     {
       title: 'Classification name',
       dataIndex: 'name',
       key: 'name',
       render(_, row) {
           return {
             children: row.name,
             props: {
               rowSpan: row.rowSpan,
             }
           }
         }
     },
]

//Table process data before importing data
<Table columns={columns} dataSource={this.createNewArr(data)}/>

Author: Huang Shida

Editor: Yuan Baiqi
Ps: please indicate the source of the quotation, thank you!

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Topics: Javascript