对象到 TreeTable 的树,按两次分组 Typescript / JavaScript

Object to Tree for TreeTable, group by twice Typescript / JavaScript

我正在尝试将列表转换为 primeng TreeTable 的树结构。

[{pk:"1", corpID:"1234", date: "31/03/21", rela:"4325", price:"20.00"},
{pk:"2", corpID:"1234", date: "21/03/21", rela:"4425", price:"50.00"} ,
{pk:"3", corpID:"3456", date: "03/03/21", rela:"6327", price:"80.00"} ,
{pk:"4", corpID:"4567", date: "05/03/21", rela:"7328", price:"40.00"}]

我需要对数据进行两次分组,第一次是 corpId,第二次是 rela。 PrimeNG TreeTable 使用 datachildren - 数据将是行中显示的值,子项将是扩展行中的数据。 https://www.primefaces.org/primeng/showcase/#/treetable 结构应该是:

{ data : [
    
        { 
            data: {
                corpID : "1234"
                },
                children: [
                   {
                   data:{ 
                     RELA: "4325"
                },
                children: [
                        {
                        data : { pk:"1",
                                 corpID:"1234",
                                 date: "31/03/21", 
                                 rela:"4325",
                                 price:"20.00"},
                        }]
                 },
                data:{ 
                   RELA: "4425"
                },
                children: [
                        {
                               { pk:"2", 
                                 corpID:"2345",
                                 date: "21/03/21",
                                 rela:"4425", 
                                 price:"50.00"
                         }
                       ]
...

我尝试过分组依据和使用 reduce 的函数,虽然它创建了正确的树结构,但它压缩了数据。 有没有办法在构建树结构的同时还包括 datachildren 属性?任何帮助将不胜感激! 我在下面尝试的函数减少了数据,我也不确定如何添加 datachildren

  let result  = this.data.reduce(this.totree, {}); 

 totree(branches, node) {

    if (!branches[node.corpId]) {
      branches[node.corpId] = {};
    }
    branches[node.corpId][node.rela] = node;
    branches[node.corpId][node.rela] = Object.assign(branches[node.corpId][node.rela]);
    return branches;
  }

我刚刚为您编写并测试了这段代码,我相信它可以更好地重构,但最重要的是它可以实现您想要的相同结构

const arr = [
  { pk: "1", corpID: "1234", date: "31/03/21", rela: "4325", price: "20.00" },
  { pk: "2", corpID: "1234", date: "21/03/21", rela: "4425", price: "50.00" },
  { pk: "3", corpID: "3456", date: "03/03/21", rela: "6327", price: "80.00" },
  { pk: "4", corpID: "4567", date: "05/03/21", rela: "7328", price: "40.00" },
];

const groupBy = (arrayInput, key) => {
  return arrayInput.reduce(
    (r, v, i, a, k = v[key]) => ((r[k] || (r[k] = [])).push(v), r),
    {}
  );
};

const groupedByCorpID = groupBy(arr, "corpID");

const ans = Object.entries(groupedByCorpID).map(([key, value]) => {
  const groupedByRela = groupBy(value, "rela");

  const children = Object.entries(groupedByRela).map(
    ([childKey, childValue]) => {
      return {
        data: { RELA: childKey },
        children: childValue,
      };
    }
  );

  return { data: { corpID: key }, children };
});