Hello I have a component that has a state that contains an object and the object contains 6 arrays:
this.state = {
obiect: {
cif: [],
data_creare: [],
detalii: [],
id: [],
id_solicitare: [],
tip: []
}
After I add values to the arrays with setState from an api call I would like to display the arrays in a HTML table.
How can I iterate through the object`s arrays so I can display them on the table rows ?
I tried this.state.obiect.map(...etc and it gives me an error.
Thanks
Here is a basic iteration using Object.entries()
const state = { obiect: { cif: [1,2], data_creare: [3,4], detalii: [5,6], id: [7,8], id_solicitare: [9, 10], tip: [11,12] } }; Object.entries(state.obiect).forEach(([k,v]) => { console.log(k, v); v.forEach(ele => console.log(ele)); });
If you want to access the arrays horizontally you can find the longest one and use a for
loop.
const state = { obiect: { cif: [1,2], data_creare: [3,4], detalii: [5,6], id: [7,8], id_solicitare: [9, 10, 13], tip: [11,12] } }; const maxL = Object.values(state.obiect).reduce((a, b) => (a = a > b.length ? a : b.length, a), 0); for (let i=0; i<maxL; i++) { let row = '' Object.entries(state.obiect).forEach(([k,v]) => { const value = v[i] ?? '-'; row += `${k}: ${value} `; }); console.log(row); }
I think you can get the different objects in object with this.state.object.slice()
. And for these objects you need .map this.state.object.id.map()
To iterate over an object's properties you can use for...in
loop :
let state = {
obiect: {
cif: [],
data_creare: [],
detalii: [],
id: [],
id_solicitare: [],
tip: []
}
}
for(let i in state.obiect){
console.log(`${i} : ${state.obiect[i]}`)
}
Try this
for (const [key, value] of Object.entries(this.state.obiect)) {
// object1[`${key}`].map(...) here for dynamic array
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.