SerbanRamon
SerbanRamon

Reputation: 107

How can I iterate through an object containing arrays in React and the object is in the state

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

Upvotes: 0

Views: 62

Answers (4)

Alan Omar
Alan Omar

Reputation: 4217

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]}`)
}

Upvotes: 0

pilchard
pilchard

Reputation: 12911

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);
}

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this

for (const [key, value] of Object.entries(this.state.obiect)) {
  // object1[`${key}`].map(...) here for dynamic array
}

Upvotes: 0

TheMB
TheMB

Reputation: 5

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()

Upvotes: 0

Related Questions