Home > front end >  React.js: how to map through nested arrays
React.js: how to map through nested arrays

Time:01-19

Lets say I have an array of objects (myContacts), In React I can map through each object of the array to get its item and index. I can use the item[key] to get it's value but what if its value is another array?.. how can I map through that?

this is what I'm trying:

const myContacts = [
   {
     name: 'John',
     hobbies: ['swimming', 'skateboard', 'TV']
   },
   {
     name: 'Sarah',
     hobbies: ['Cooking'],
   },
   {
     name: 'Cindy',
     hobbies: ['Shopping', 'Running'],
   },
];
 
function MyPeeps({ myContacts }) {
  return (
    <div>
      {myContacts.map((item, index) => {
        return (
          <div key={index}>
            <p>{item.name}</p>
            {item.hobbies &&
              <ul>
                //if there is a hobbies array for this person, then list each as an `li`
              </ul>
            }
          </div>
        )
      })}
    </div>
  )
}


CodePudding user response:

Generally speaking, you can just do the same:

<ul>{item.hobbies.map(i => <li>i</li>)}</ul>

But a better idea could be to create a Contact component to avoid excessive nesting, then delegate to it:

<div key={index}>
    <Contact item={item} />
</div>

CodePudding user response:

You can also use item.hobbies.length > 0 if you're sure that the hobbies array is always present.

function MyPeeps({ myContacts }) {
  return (
    <div>
      {myContacts.map((item, index) => {
        return (
          <div key={index}>
            <p>{item.name}</p>
            {item.hobbies && (
              <ul>
                {item.hobbies.map((hobby) => (
                  <li key={hobby}>{hobby}</li>
                ))}
              </ul>
            )}
          </div>
        );
      })}
    </div>
  );
}

CodePudding user response:

      { 
       item.hobbies.length>0 &&
          <ul>
              item.hobbies.map((hobby,index)=>{
              return <li key={index}>{hobby}</li>
               })
          </ul>
        }
  • Related