Question

Get data from Fetch to apply if statement

Posted May 26, 2021 113 views
JavaScript

I Beginner in JavaScript, I’m trying to apply an If to a value that I got through fetch but gave me this error “script.js:41 Uncaught (in promise) TypeError: Cannot read property ‘substr’ of undefined at datos (script.js:41)”. I need to store in a new array only the data in base a specific date. How can I take the data from fetch and don’t have to wait for the data to be load. I hope you can understand me.

const fecha = new Date();
const today = fecha.getDate();
const year = fecha.getFullYear();
const month = fecha.getMonth() + 1;
const date = `${month}/${today}/${year}`;



fetch('./file.txt')
    .then(response => response.text()
        .then(data => {

            let info = new Array();
            info = datos(data);



    }));


//Function get Array data
async function datos(data) {

    let arrayLineas = new Array();
    let arrayColumnas = new Array();
    let arrayFiltered = new Array();

    let texto = data;
    arrayLineas = texto.split(/\n|\r/).splice(11);
    for (let i = 0; i < arrayLineas.length; i++) {
        arrayColumnas[i] = arrayLineas[i].split("^");

    }

    for (let x = 0; x < arrayColumnas.length; x++) {
        let date_db = "";
        date_db = arrayColumnas[x][17];

        //console.log(date_db.substr(0,10));
//In this "If"  is where the error happened
        if (date === date_db.substr(0,10)) {
            console.log(date);
        }



    }

}
edited by bobbyiliev

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Interesting achive, thanks for sharing