Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in assigning elements in array in JS

i am trying to store list data into an object received from axios response. the first set of data being headers i am storing in cols as array and the rest in rows. The data received is all defined and after parsing it perfectly logged in the console ie all defined. inside the loop when loading of rows elements starts, the first set of elements gets stored but for the next set ie for the value of i = 2 I am getting error saying cannot set property of undefined (setting 0).

For convenience I have changed the type of data received from the axios

        let response = {data:'"A","B"\n"C","D"\n"E","F"'} //await axios(URL)
        let raw = response.data.split(/\r?\n/);
        let data = {
            cols:[],
            rows:[]   // I have tried rows:[[]] or rows:[{v:[]}]
        }

        for (let i in raw) {
            raw[i] = raw[i].split(",");
            for(let j in raw[i]){
                raw[i][j] = raw[i][j].replace(/"/g, '')
                if (i==0)
                    data.cols[j]=raw[i][j]
                else{
                    data.rows[i-1][j]=raw[i][j] // for rows as object => data.rows[i-1].v[j]
                    //console.log(i+'->'+data.rows[i-1])
                }
            }        
        }
        return data // this is not matter of concern
    }   

I have tried declaring the row array as 2D array but error persists. hoving the mouse over the object gives rows (property) : never[] and same with cols.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do something like this

let response = {data:'"A","B"\n"C","D"\n"E","F"'}

const [cols, ...rows] = response.data.split('\n').map(r => r.replace(/"/g, '').split(','))

const data = {
  cols,
  rows
}

console.log(data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading