Home > Back-end >  How to map loop an object Array with nested object Arrays?
How to map loop an object Array with nested object Arrays?

Time:10-15

I have some data I want to render that looks like this: enter image description here

How can I map loop the entire CarParts array and then map loop the nested tyres array inside it and still maintain their respective index order?

{CarParts.map((parts, index) => (
  <div key={index}>
    {parts.system && (
      <div className="bg-red-500">
        <p>{parts.system}</p>
      </div>
    )}

    {parts.tyres && (
      <>
        {parts.tyres.map((tyre, index) => (
          <div className="bg-green-500" key={index}>
            <p>Tyre: {tyre}</p>
          </div>
        ))}
      </>
    )}

Output in browser should look like this:

System: Engine

Tyre: Bridgestone

Tyre: Michelin

Tyre: Goodyear

System: Exhaust Pipe

CodePudding user response:

{carParts.map((parts) => {
                              return (
                                 <div>
                                    {!Array.isArray(parts) && (
                                       <div>System :{parts.system}</div>
                                    )}
                                    {Array.isArray(parts) && (
                                       <div>
                                          {parts.map((tyre) => {
                                             return (
                                                <div>Tyre: {tyre.tyres}</div>
                                             )
                                          })}
                                       </div>
                                    )}
                                 </div>
                              )
                           })}

check element is array, then map again.

CodePudding user response:

Contrary to what your code suggests, your object array does not have objects with a tyres property that is an array. Instead, your array seems to either have single-property objects or arrays with such objects.

So if your intention is to just output the objects without regard of whether they exist at the first or second level of arrays, then just flatten the array first.

The basic structure of your code then becomes:

{CarParts.flat().map(part => (
    <div>
      <p>{Object.entries(part)[0].join(": ")}</p>
    </div>
))}

Again, this assumes that the actual plain objects each have only one property and value, as is suggested by the image of the data structure.

  • Related