Search code examples
javascriptreactjsecmascript-6ecmascript-5

How to map an Array of objects, that have arrays in the objects


My question is a bit hard to explain in the title.. but in react, I'm trying to map an element that looks like this

[
  { 
    logicLayer: { name: someName, etc }, 
    subComps: [ { name: anotherName, etc },{ name: anotherName, etc } ]
  },
  { 
    logicLayer: { name: someName, etc }, 
    subComps: [ { name: anotherName, etc },{ name: anotherName, etc } ]
  },
  etc
]

To a dropdown button menu

// This Works Fine

return (
        singular.buttonGroups.map(( buttonGroup, index1 ) =>
          buttonGroup.subComps.map(( subComp, index2 ) =>
            <MenuItem key={index2}><b>{buttonGroup.logicLayer.name}:</b> {subComp.name}</MenuItem>
          )
        )
      );

But what I really want to do is put a "divider" after it iterates the inner array.. something like this

// This Doesn't Work

return (
        singular.buttonGroups.map(( buttonGroup, index1 ) =>
          buttonGroup.subComps.map(( subComp, index2 ) =>
            <MenuItem key={index2}><b>{buttonGroup.logicLayer.name}:</b> {subComp.name}</MenuItem>
          )
            <MenuItem divider></MenuItem>  // THIS LINE DOESN'T WORK
        )
      );

How can I map this properly so that I can put a divider after it iterates the array of one of its objects?

EDIT: would be nice if there is a solution out there that doesn't require me to wrap it in a div container


Solution

  • You need to wrap it with some container:

    return (
        singular.buttonGroups.map(( buttonGroup, index1 ) =>
          <div> 
              {buttonGroup.subComps.map(
                 ( subComp, index2 ) =>
                    <MenuItem key={index2}><b>{buttonGroup.logicLayer.name}:</b> {subComp.name}</MenuItem>
              )}
              <MenuItem divider></MenuItem>  // THIS LINE DOESN'T WORK
          </div>
        )
      );