簡體   English   中英

將對象數組轉換為 antd 表列?

[英]Convert an array of object to antd table columns?

我有一個對象數組,我需要將其轉換為 antd 表列格式。 這是在線編輯器鏈接

 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, // }, // ]

要實現您想要的,幾乎沒有什么可做的。 根據Ant Design 文檔,您的數據不需要轉換為output 它可以直接用作dataSource數組。 您需要提供columns數組,如下所示:

 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} />;

使用columns數組,您可以定義要在表中顯示的dataSource元素的哪個屬性。 title屬性定義要在每個列標題中顯示的標題。

根據您提供的內容,我猜您正在嘗試從給定的數據源中自動提取列名。 這是您要查找的內容(我重用了名為a的變量:

const columns = Object.keys(a[0]||{})
    .map(key => ({dataIndex: key, key, title: key}));

<Table dataSource={a} columns={columns} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM