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

How to iterate the array inside array of object in react js?

I am trying to iterate the data but it saying testData is not iterable.
This is my code –

const testData = details?.[0]?.one?.map((item) => {
    const labelTwo =
      item?.itemType === 'FIRST' ? 'newLabel' : 'oldLabel';
    return {
      label: details?.[0]?.one?.length > 1 ? labelTwo : 'labelOne',
      value: item?.value,
    };
  });
  const myData: Item[] = [
    ...testData,
    {
      label: 'first',
      value: 'firstValue',
    },
    isVisible && {
      label: 'second',
      value: 'secondValue',
    },
  ];
return (
  <>
    {myData?.map((item: Item) => {
      return (
       <div>
        <div>{item?.label}</div>
        <div>{item?.value}</div>
       </div>
      );
    }
  </>
)

Below in return when I am trying to iterate myData using map function then it is saying testData is not iterable.
Am I doing anything wrong ? what will be the best approach here to iterate the data

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 :

As @cmgchess mentioned, the error "testData is not iterable" happens because you are trying to spread an object that is not iterable.

Looking at your code, the most likely cause is that testData is undefined.

Try this:

const testData = details?.[0]?.one?.map((item) => {
  const labelTwo = item?.itemType === 'FIRST' ? 'newLabel' : 'oldLabel';
  return {
    label: details?.[0]?.one?.length > 1 ? labelTwo : 'labelOne',
    value: item?.value,
  };
}) || []; // Default to empty array if undefined
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