Skip to content
Advertisement

Adding an object conditionally inside an array

I want to add a conditional object inside an array of objects. If the condition is not met, I want it as if that object is not there AT ALL, while keeping the other objects as they are. Consider the following:

const CardBuildingBlock: FC = () => {
    const type = 'typeA';

    const typesOfCards = [
      {name: 'Card A'
      size: 'Medium'
      action: 'make'},

      {name: 'Card B'
      size: 'Small'
      action: 'break'},

      {name: 'Card C'
      size: 'Large'
      action: 'build'},

//I tried doing the following but it doesn’t work

      type == 'typeA' ? null : {
      name: 'Card A'
      size: 'Medium'
      action: 'make'},
    ];


    return(
      typeOfCards.map(({name, size, action}) => (
        <BuildCard 
          name = {name}
          size = {size}
          action = {action}
        />
    )
)};

Please Help.!!!

Thanks for the help.

Advertisement

Answer

From what I understood, you want to filter away all the elements of the array given a condition. What I would do is adding a new key to the object specifying if it should be displayed, and then filter & map.

const typesOfCards = [
  { name: "Card A", size: "Medium", action: "make", type: "typeA" },
  ...
];
return typesOfCards.filter(card => card.type === "typeA").map(({ name, size, action }) => (
    <BuildCard name={name} size={size} action={action} />
  ));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement