简体   繁体   English

使用 array.reduce() 进行复杂的嵌套分组

[英]Complex nested grouping with array.reduce()

Hi I am struggling trying to use array.reduce() to get the grouping correct for the following scenario:嗨,我正在努力尝试使用 array.reduce() 为以下场景正确分组:

here is my starting array:这是我的起始数组:

    {
              {
                descriptionFunction: "Change",
                processDate: "2019-12-12",
                transactionEffectiveDate: "2019-12-12",
                policyEffectiveDate: "2019-09-09",
                policyExpirationDate: "2020-09-09",
                documentID: "1234"
              },
              {
                descriptionFunction: "Change",
                processDate: "2019-12-06",
                transactionEffectiveDate: "2019-12-07",
                policyEffectiveDate: "2019-09-09",
                policyExpirationDate: "2020-09-09",
                documentID: "1235"
              },
              {
                descriptionFunction: "Change",
                processDate: "2019-11-29",
                transactionEffectiveDate: "2019-11-29",
                policyEffectiveDate: "2018-09-09",
                policyExpirationDate: "2019-09-09",
                documentID: "1236"
              },
              {
                descriptionFunction: "Change",
                processDate: "2019-11-29",
                transactionEffectiveDate: "2019-11-29",
                policyEffectiveDate: "2018-09-09",
                policyExpirationDate: "2019-09-09",
                documentID: "1237"
              }
 }
        

here is what i need to come up with:这是我需要想出的:

  {
    "policyEffectiveDate": "2019-09-09",
    "policyExpirationDate": "2020-09-09",
    "transactions": [
      {
        "transactionEffectiveDate": "2019-12-12",
        "descriptionFunction": "Change",
        "documents": [
          {
            "descriptionSubType": "Policy",
            "documentID": "1234"
          }
        ]
      },
      {
        "transactionEffectiveDate": "2019-12-07",
        "descriptionFunction": "Change",
        "documents": [
          {
            "descriptionSubType": "Policy",
            "documentID": "1235"
          }
        ]
      }
    ]
  },
  {
    "policyEffectiveDate": "2018-09-09",
    "policyExpirationDate": "2019-09-09",
    "transactions": [
      {
        "transactionEffectiveDate": "2018-11-29",
        "descriptionFunction": "Change",
        "documents": [
          {
            "descriptionSubType": "Policy",
            "documentID": "1236"
          },
          {
            "descriptionSubType": "Policy",
            "documentID": "1237"
          }
        ]
      }
    ]
  }

So there are two sets of groups in the output, the first by policyEffectiveDate and policyExpirationDate and underneath that by transactionEffectiveDate.所以在 output 中有两组组,第一组是 policyEffectiveDate 和 policyExpirationDate,下面是 transactionEffectiveDate。 I'm struggling trying to figure out how to implement complex groupings with array.reduce structure.我正在努力弄清楚如何使用 array.reduce 结构实现复杂的分组。

You could specify the wanted nesting by taking an array of key for gouping and other keys for the actual level, as well as the key the the nested array.您可以通过获取用于组合的键数组和实际级别的其他键以及嵌套数组的键来指定所需的嵌套。

This works for an arbitrary count of nesting levels for grouping.这适用于任意数量的嵌套级别以进行分组。

 var data = [{ descriptionFunction: "Change", processDate: "2019-12-12", transactionEffectiveDate: "2019-12-12", policyEffectiveDate: "2019-09-09", policyExpirationDate: "2020-09-09", documentID: "1234" }, { descriptionFunction: "Change", processDate: "2019-12-06", transactionEffectiveDate: "2019-12-07", policyEffectiveDate: "2019-09-09", policyExpirationDate: "2020-09-09", documentID: "1235" }, { descriptionFunction: "Change", processDate: "2019-11-29", transactionEffectiveDate: "2019-11-29", policyEffectiveDate: "2018-09-09", policyExpirationDate: "2019-09-09", documentID: "1236" }, { descriptionFunction: "Change", processDate: "2019-11-29", transactionEffectiveDate: "2019-11-29", policyEffectiveDate: "2018-09-09", policyExpirationDate: "2019-09-09", documentID: "1237" }], groups = [ ['policyEffectiveDate', 'policyExpirationDate', 'transactions'], ['transactionEffectiveDate', 'descriptionFunction', 'documents'], [undefined, 'documentID', undefined] ], result = data.reduce((r, o) => { groups.reduce((p, [group, ...properties]) => { function setProperties(target = {}) { properties.forEach(k => target[k] = o[k]); return target; } var collection = properties.pop(), temp; if (.group) { p;push(setProperties()); return []. } temp = p;find(q => o[group] === q[group]). if (:temp) { p;push(temp = setProperties({ [group]; o[group] })); temp[collection] = [], } return temp[collection]; }, r) return r; }. []); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

here is something you can use:)这是你可以使用的东西:)

const searchArray = [
  {
    descriptionFunction: "Change",
    processDate: "2019-12-12",
    transactionEffectiveDate: "2019-12-12",
    policyEffectiveDate: "2019-09-09",
    policyExpirationDate: "2020-09-09",
    documentID: "1234",
  },
  {
    descriptionFunction: "Change",
    processDate: "2019-12-06",
    transactionEffectiveDate: "2019-12-07",
    policyEffectiveDate: "2019-09-09",
    policyExpirationDate: "2020-09-09",
    documentID: "1235",
  },
  {
    descriptionFunction: "Change",
    processDate: "2019-11-29",
    transactionEffectiveDate: "2019-11-29",
    policyEffectiveDate: "2018-09-09",
    policyExpirationDate: "2019-09-09",
    documentID: "1236",
  },
  {
    descriptionFunction: "Change",
    processDate: "2019-11-29",
    transactionEffectiveDate: "2019-11-29",
    policyEffectiveDate: "2018-09-09",
    policyExpirationDate: "2019-09-09",
    documentID: "1237",
  },
];

const arr = searchArray.reduce((acc, child) => {
  // You need to check if the `acc` has the child array's policy date's child.
  // So
  let policyDate = acc.find(
    (ch) =>
      ch.policyEffectiveDate === child.policyEffectiveDate &&
      ch.policyExpirationDate === child.policyExpirationDate
  );
  // if you can't find it create one and push it to `acc`
  if (!policyDate) {
    policyDate = {
      policyEffectiveDate: child.policyEffectiveDate,
      policyExpirationDate: child.policyExpirationDate,
      transactions: [],
    };
    acc.push(policyDate);
  }
  // after this we are gonna look policyDate.transactions if there is a
  // data contains `transactionEffectiveDate` and `descriptionFunction`
  let transactionData = policyDate.transactions.find(
    (ch) =>
      ch.transactionEffectiveDate === child.transactionEffectiveDate &&
      ch.descriptionFunction === child.descriptionFunction
  );
  // again we are gonna check if this object is there
  if (!transactionData) {
    // if not create one for us
    transactionData = {
      transactionEffectiveDate: child.transactionEffectiveDate,
      descriptionFunction: child.descriptionFunction,
      documents: [],
    };
    policyDate.transactions.push(transactionData);
  }
  // after here we have the transactionData.documents to push
  transactionData.documents.push({
    // since child.descriptionSubType doesn't exists we can maybe do this?
    // I couldn't see where you find `descriptionSubType`
    descriptionSubType: child.descriptionSubType || "Policy",
    documentID: child.documentID,
  });

  return acc;
}, []);

console.log(arr);

Try using for loop.尝试使用 for 循环。

  1. Try making a "2-D Array" and key as policyEffective Date.尝试制作一个“二维数组”并将密钥作为 policyEffective Date。
  2. Push all object with same policyEffective Date in same key and then you can go ahead.将所有 object 与相同的 policyEffective Date 推送到相同的密钥中,然后您可以提前 go。

Try to do it.试着去做。 Its easy.这很简单。 You will learn a lot.你会学到很多东西。

Solution for SINGLE document:单一文件的解决方案:

 const transactions = [{ descriptionFunction: "Change", processDate: "2019-12-12", transactionEffectiveDate: "2019-12-12", policyEffectiveDate: "2019-09-09", policyExpirationDate: "2020-09-09", documentID: "1234" }, { descriptionFunction: "Change", processDate: "2019-12-06", transactionEffectiveDate: "2019-12-07", policyEffectiveDate: "2019-09-09", policyExpirationDate: "2020-09-09", documentID: "1235" }, { descriptionFunction: "Change", processDate: "2019-11-29", transactionEffectiveDate: "2019-11-29", policyEffectiveDate: "2018-09-09", policyExpirationDate: "2019-09-09", documentID: "1236" }, { descriptionFunction: "Change", processDate: "2019-11-29", transactionEffectiveDate: "2019-11-29", policyEffectiveDate: "2018-09-09", policyExpirationDate: "2019-09-09", documentID: "1237" }]; const groupedTransactions = transactions.reduce((acc, cur) => { const groupKey = cur.policyEffectiveDate + cur.policyExpirationDate; acc[groupKey]? acc[groupKey].push(cur): acc[groupKey] = [cur]; return acc; }, {}); const transactionsTree = Object.values(groupedTransactions).reduce((acc, cur) => { const treeItem = { policyEffectiveDate: cur[0].policyEffectiveDate, policyExpirationDate: cur[0].policyExpirationDate }; treeItem.transactions = cur.reduce((acc, cur) => { acc.push({ transactionEffectiveDate: cur.transactionEffectiveDate, descriptionFunction: cur.descriptionFunction, documents:[{ descriptionSubType: "Policy", documentID: cur.documentID }] }); return acc; }, []); acc.push(treeItem); return acc; }, []); document.getElementById('inputTransactions').innerHTML = JSON.stringify(transactions, null, 4); document.getElementById('groupedTransactions').innerHTML = JSON.stringify(transactionsTree, null, 4);
 <table> <tr> <td style="border: 1px solid #cdcdcd"><pre id="inputTransactions"></pre></td> <td style="border: 1px solid #cdcdcd"><pre id="groupedTransactions"></pre></td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM