1

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.

3
  • Can you share what is the result you want to get? Commented Jun 10, 2022 at 8:38
  • {cols:['A','B'], rows:[['C','D'],['E','F']]} something like that Commented Jun 10, 2022 at 8:39
  • if variable raw is storing data as an array then do not use for in loop rather than use forEach or map or normal for loop or while. Commented Jun 10, 2022 at 9:57

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.