如何從數組動態建立表?
P粉724737511
P粉724737511 2023-09-15 10:47:48
0
1
567

我有一個用例來建立一個包含動態資料(包括標題名稱)的表。我嘗試了多種方法從API回應中重建數組,但仍然無法開發它。

從回應接收陣列如下

[
   {
      "category": "Emergency services",
      "code": "RMY 90",
      "limit": "9032",
      "OT": "4124"
   },
   {
      "category": "Pediatrician",
      "code": "RMY 80",
      "limit": "1232",
      "OT": "9412"
   },
   {
      "category": "Neurology",
      "code": "RMY 70",
      "limit": "6423",
      "OT": "7312"
   }
]

網格預期陣列

[
   {
      "item": "Block Code",
      "Emergency services": "RMY 90",
      "Pediatrician": "RMY 80",
      "Neurology": "RMY 70"
   },
   {
      "item": "Total Capacity",
      "Emergency services": "9032",
      "Pediatrician": "1232",
      "Neurology": "6423"
   },
   {
      "item": "OT Capacity",
      "Emergency services": "4124",
      "Pediatrician": "9412",
      "Neurology": "7312"
   }
]

表格範例

我嘗試過使用 Object.keys() 和 map 但無法正確建構陣列。由於程式碼位於客戶端系統中,我無法共用它。請幫我重建數組。

我的程式碼是

const rowList = ["Block Code", "Total Capacity", "OT Capacity"];
  let arr = [];
  const dumming = rowList?.forEach(item => {

    for (const [key, object] of Object.entries(responseData)) {
      let x = [];
      Object.keys(object)?.forEach(item => {
        x.push(object[item]);
      });
      // console.log('rrrr', x);
    }

    let val = responseData.map((ned, index) => {
      let x = {};
      Object.keys(object)?.forEach(item => {
        x = ned[item]
      });
      // let cor = Object.entries(ned).map(([key, leaf]) => key+leaf);
      return {
        id: `${ index }-${ item }`,
        name: item, ...x
      };
    });
    arr.push(val);
  });

  console.log(arr);

我不確定這是否正確。陷入困境

P粉724737511
P粉724737511

全部回覆(1)
P粉415632319

使用rowList 的想法很好,但它假設輸入物件中存在一些關鍵順序(當您稍後需要將資料與每個標籤關聯時),這通常是一個壞主意依賴於普通物件中的某些順序

但是,您的rowList 沒有任何作用:儘管您迭代它,但您的程式碼從不使用item (它定義了其他item 變量)。

其次,.map 回呼中有一個未知變數 object

我不懂為什麼你會產生一個有idname 鍵的對象,並產生格式為${ index }-${ item } 的字串 因為這與您問題中的任何內容都不符。

以下是我建議的做法:

const responseData = [{"category": "Emergency services","code": "RMY 90","limit": "9032","OT": "4124"},{"category": "Pediatrician","code": "RMY 80","limit": "1232","OT": "9412"},{"category": "Neurology","code": "RMY 70","limit": "6423","OT": "7312"}];

const rowList = [["code", "Block Code"], ["limit", "Total Capacity"], ["OT", "OT Capacity"]];
const result = rowList.map(([key, item]) => ({
    item,
    ...Object.fromEntries(responseData.map((obj) => [obj.category, obj[key]]))
}));

console.log(result);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板