Home > Blockchain >  Error in assigning elements in array in JS
Error in assigning elements in array in JS

Time:06-10

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.

CodePudding user response:

You can do:

const response = { data: '"A","B"\n"C","D"\n"E","F"' }
const [cols, ...rows] = response.data.split(/\r?\n/).map(r => r.match(/[A-Z] /g))
const data = { cols, rows }

console.log(data)

CodePudding user response:

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)

  • Related