编辑代码

function splitIntoCustomsDeclarations(data) {
    const result = [];
    const groupedByLicense = {};

    const withLicense = data.filter(item => item.importLicense);
    const withoutLicense = data.filter(item => !item.importLicense);

    // Step 1: 按进口许可证号分组,将无许可证号商品和同许可证号的商品分在同一组
    withLicense.forEach(item => {
        const license = item.importLicense || 'NO_LICENSE';
        if (!groupedByLicense[license]) {
            groupedByLicense[license] = [];
        }
        groupedByLicense[license].push(item);
    });

    const licenseKeys = Object.keys(groupedByLicense);
    if (licenseKeys.length > 0) {
        const lastKey = licenseKeys[licenseKeys.length - 1];
        groupedByLicense[lastKey].push(...withoutLicense);
    } else {
        groupedByLicense["No License"] = withoutLicense;
    }


    // Step 2: 在每个许可证号组中,根据美国排除编号分组
    for (const license in groupedByLicense) {
        const itemsByLicense = groupedByLicense[license];

        // 分离有美国排除编号的和没有美国排除编号的
        const withExclusion = {};
        const withoutExclusion = [];

        itemsByLicense.forEach(item => {
            const exclusionNumber = item.usExclusionNumber;
            if (exclusionNumber) {
                // 如果有美国排除编号,根据排除编号进行分组
                if (!withExclusion[exclusionNumber]) {
                    withExclusion[exclusionNumber] = [];
                }
                withExclusion[exclusionNumber].push(item);
            } else {
                // 如果没有美国排除编号,则放入没有排除编号的组
                withoutExclusion.push(item);
            }
        });

        // Step 3: 生成报关单,将每个美国排除编号组作为一个单独的报关单
        for (const exclusionNumber in withExclusion) {
            result.push(withExclusion[exclusionNumber]);
        }

        // 如果有没有排除编号的商品,把它们放入一个单独的报关单
        if (withoutExclusion.length > 0) {
            result.push(withoutExclusion);
        }
    }
    return result;
}

// 示例数据
const data = [
    { importLicense: 'LIC001', usExclusionNumber: 'EXC001', description: 'Item 1' },
    { importLicense: 'LIC001', usExclusionNumber: 'EXC002', description: 'Item 2' },
    { importLicense: 'LIC002', usExclusionNumber: 'EXC001', description: 'Item 3' },
    { importLicense: 'LIC002', usExclusionNumber: null, description: 'Item 4' },
    { importLicense: 'LIC001', usExclusionNumber: null, description: 'Item 5' },
    { importLicense: null, usExclusionNumber: null, description: 'Item 6' },
    { importLicense: null, usExclusionNumber: 'EXC003', description: 'Item 7' }
];

// 调用函数并输出结果
const splitData = splitIntoCustomsDeclarations(data);
console.log(splitData);