Javascript 数组解决方案

问题描述 投票:0回答:1

我有一个多维动态 JSON 数组:示例 -

{
    "TEST": [{
        "_DocumentType": "INVOICE",
        "_DocumentDate": "2022-12-31",
        "_AccountNumber": "910:11:77:44520",
        "_DocumentNumber": "BILL-3270",
        "Detail": [{
                "test": "INVOICE",
                "test2": "2022-10-21"
            },
            {
                "test": "INVOICE",
                "test2": "2022-10-21"
            }
        ]
    }, {
        "_DocumentType": "INVOICE",
        "_DocumentDate": "2022-12-31",
        "_AccountNumber": "910:11:77:44520",
        "_DocumentNumber": "BILL-2543",
        "Detail": [{
                "test": "INVOICE",
                "test2": "2022-12-31"
            },
            {
                "test": "INVOICE",
                "test2": "2022-12-31"
            }
        ]
    }, {
        "_DocumentType": "INVOICE",
        "_DocumentDate": "2022-12-31",
        "_AccountNumber": "910:11:77:44520",
        "_DocumentNumber": "BILL-3270",
        "Detail": [{
                "test": "INVOICE",
                "test2": "2022-12-31"
            },
            {
                "test": "INVOICE",
                "test2": "2022-12-31"
            }
        ]
    }]
}

如果 _DocumentNumber 在任何数组中都相同,则它们与如果不同的 _DocumentNumber 则与其他数组组合

javascript arrays multidimensional-array
1个回答
-1
投票

您可以使用嵌套循环遍历 JSON 数组中的每个对象,并将它们的 _DocumentNumber 值与数组中的其他对象进行比较。如果找到匹配项,您可以通过合并它们的 Detail 数组将对象合并为一个,并从数组中删除重复的对象。

这是 JavaScript 中的示例实现。

此代码将输出一个新的 JSON 对象,其中包含基于 _DocumentNumber 值的组合对象。

const data = { "TEST": [{ "_DocumentType": "INVOICE", "_DocumentDate": "2022-12-31", "_AccountNumber": "910:11:77:44520", "_DocumentNumber": "BILL-3270", "Detail": [{ "test": "INVOICE", "test2": "2022-10-21" }, { "test": "INVOICE", "test2": "2022-10-21" } ] }, { "_DocumentType": "INVOICE", "_DocumentDate": "2022-12-31", "_AccountNumber": "910:11:77:44520", "_DocumentNumber": "BILL-2543", "Detail": [{ "test": "INVOICE", "test2": "2022-12-31" }, { "test": "INVOICE", "test2": "2022-12-31" } ] }, { "_DocumentType": "INVOICE", "_DocumentDate": "2022-12-31", "_AccountNumber": "910:11:77:44520", "_DocumentNumber": "BILL-3270", "Detail": [{ "test": "INVOICE", "test2": "2022-12-31" }, { "test": "INVOICE", "test2": "2022-12-31" } ] }] };

const result = [];
for (let i = 0; i < data.TEST.length; i++) {
  const obj = data.TEST[i];
  const docNum = obj._DocumentNumber;
  let combinedObj = obj;
  for (let j = i + 1; j < data.TEST.length; j++) {
    const otherObj = data.TEST[j];
    if (otherObj._DocumentNumber === docNum) {
      combinedObj = { ...combinedObj, Detail: [...combinedObj.Detail, ...otherObj.Detail] };
      i++;
    }
  }
  result.push(combinedObj);
}
console.log({
  TEST: result
});

© www.soinside.com 2019 - 2024. All rights reserved.