1

I'm using Framer X (which uses react) to generate a bunch of components. I have an array of objects like so:

const chosenBets = [{}, { id: 1
 label: "X"
 odd: 2.63
 oddIndex: 1
 team_home: "Bournemouth"
 team_away: "West Ham United"
 matchCardIndex: 1}]

I'm then mapping through the array:

        {props.chosenBets.map((match, i) => {
            return (
                <div key={i}>
                    {i}
                </div>
            )
        })}

The result will be generating two divs, seems the length of the array is 2. How do I make it so that only non-empty objects are rendered?

a7dc
  • 3,323
  • 7
  • 32
  • 50

2 Answers2

2

Just check if objects are non-empty in map. Alternatively, use .filter().

{props.chosenBets.map((match, i) => {
  if (Object.keys(match).length !== 0
    return (
      <div key={i}>
        {i}
      </div>
    );
})}
Dragos Strugar
  • 1,314
  • 3
  • 12
  • 30
2

simply use filter first and then map

{props.chosenBets.filter(v=> Object.keys(v).length).map((match, i) => {
       return (
       <div key={i}>
           {i}
       </div>
     )
 })}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60