I have an array of object and i need to convert that into antd table columns format. Here is the online editor link.
const a = [
{
id: 1,
startValue: 1,
endValue: 3,
box: "ele",
},
{
id: 2,
startValue: 3,
endValue: 5,
box: "vcu",
},
{
id: 3,
startValue: 2,
endValue: 6,
box: "mcu",
},
]
// output
// [
// {
// dataindex: id,
// key: id,
// title: id,
// },
// {
// dataindex: startValue,
// key: startValue,
// title: startValue,
// },
// {
// dataindex: endValue,
// key: endValue,
// title: endValue,
// },
// {
// dataindex: box,
// key: box,
// title: box,
// },
// ]
CodePudding user response:
There is little to do to achieve what you want. According to Ant Design documentation your data does not need to be converted into output
. It can directly be used as the dataSource
array. And you will need to supply the columns
array as shown below:
const dataSource = [
{
id: 1,
startValue: 1,
endValue: 3,
box: "ele",
},
{
id: 2,
startValue: 3,
endValue: 5,
box: "vcu",
},
{
id: 3,
startValue: 2,
endValue: 6,
box: "mcu",
}
];
const columns=
[
{
dataindex: "id",
key: "id",
title: "Id"
},
{
dataindex: "startValue",
key: "startValue",
title: "Start value"
},
{
dataindex: "endValue",
key: "endValue",
title: "End value"
},
{
dataindex: "box",
key: "box",
title: "Box"
}
];
// the following JSX expression will create the ant table in a React environment:
<Table dataSource={dataSource} columns={columns} />;
With the columns
array you define which property of the dataSource
elements you want to display in the table. The title
property defines the title to be shown in each column header.
CodePudding user response:
Based on what you provided, I guess you are trying to automatically extract the column names from the given dataSource. Here is what you are looking for (I reused the variable named a
:
const columns = Object.keys(a[0]||{})
.map(key => ({dataIndex: key, key, title: key}));
<Table dataSource={a} columns={columns} />