如何从数组动态创建表?
P粉724737511
P粉724737511 2023-09-15 10:47:48
0
1
550

我有一个用例来创建一个包含动态数据(包括标题名称)的表。我尝试了多种方法从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);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板