При сопоставлении каждое значение устанавливается на последнее возвращаемое значение [Node JS] - PullRequest
0 голосов
/ 08 мая 2020

Я всю ночь писал это, и кажется, что fixedFile повторяет последнее значение, возвращаемое TransformElement в каждом экземпляре массива.

Программа должна принимать CSV определенного типа, измените номера телефонов на правильный формат, а затем выведите его в формате CSV. Я не могу показать вам результат, потому что файлы содержат личную информацию, но все работает, кроме описанной мной проблемы.

Я предполагаю, что это как-то связано с переменным временем жизни, но я не уверен. Пожалуйста, помогите мне здесь.

const CSVToJson = require('csvtojson');
const JSONToCSV = require('json2csv').parse;
const FS = require('fs');

const referenceJSON = {
    'Student First Name': '',
    'Student Last Name': '',
    'Mother\'s Name': '',
    'Mother\'s Phone Number': '',
    'Father\'s Name': '',
    'Father\'s Phone Number': '',
    'Primary Phone Number': '',
    'Emergency Contact': '',
    'Emergency Contact Phone Number': '',
    'Street Address': '',
    'City': '',
    'Zip': '',
    'Email Address': ''
}

TransformCSV('./source.csv'); // Will be changeable through HTML

function TransformCSV(filePath) {

    CSVToJson().fromFile(filePath).then(source => {

        const fixedFile = source.map(src => FixElements(src));
        console.log(fixedFile);

        const csv = JSONToCSV(fixedFile, {
            fields: [
                "Student First Name",
                "Student Last Name",
                "Mother\'s Name",
                "Mother\'s Phone Number",
                "Father\'s Name",
                "Father\'s Phone Number",
                "Primary Phone Number",
                "Emergency Contact",
                "Emergency Contact Phone Number",
                "Street Address",
                "City",
                "Zip",
                "Email Address"]
        });

        console.log(csv);

        //FS.writeFileSync("./newCSV.csv", csv)
    });
}

function FixElements(src) {
    let newFile = referenceJSON;

  // This fixes some inconsistencies in the csv
    for (let key in src) {
        let newString = key;
        if (newString.endsWith(':')) {
            newString.trim();
            newString = key.replace(':', '');
        }


        newFile[newString] = src[key];
    }

  // This fixes the phone number to the correct format
    const PrunePhoneNumber = (num) => {
        let phoneNum = newFile[num];

        for (let i = 0; i < phoneNum.length; i++ || phoneNum.charAt(i) === ' ' || phoneNum.charAt(i) === 'o') {
            if (isNaN(parseInt(phoneNum.charAt(i)))) {
                phoneNum = phoneNum.substr(0, i) + phoneNum.substr(i + 1, phoneNum.length);
            }
        }
        phoneNum.trim();

        phoneNum = `(${phoneNum.substr(0, 3)}) ${phoneNum.substr(3, 3)}-${phoneNum.substr(6, 4)}`;


        newFile[num] = phoneNum;

    }

    PrunePhoneNumber("Primary Phone Number");
    PrunePhoneNumber("Mother\'s Phone Number");
    PrunePhoneNumber("Father\'s Phone Number");
    PrunePhoneNumber("Emergency Contact Phone Number");

    return newFile;
}
...