Search code examples
javascriptarraysreactjsframerjs

mapping through all non-empty objects in react


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?


Solution

  • 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>
        );
    })}