0
votes

I am trying to map an array of typescript interface objects and print its values in a table. My array looks something like this:

export interface data {
                fields?: field[];
            }

export interface field {
                name: string;
                description: string;
                subfields: subfield[];
            }

But I want to print only that field which has field.name equal to requiredName

On usage of ternary operator to define condition I am getting the following error: Expected an assignment or function call and instead saw an expression

I would appreciate some help in defining conditional statements to map my object. I have used ternary operator before too but only for printing value in a table cell instead of dynamically creating one.

Here´s my code so far:

           <Table>
            <TableBody>
              <TableRow >
                <TableCell>
                {props.fields.map((it) =>
                  {it.name===requiredName ? (
                    <Table>...</Table>
                  ) : (
                    null
                  )}
                )} 
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>

Thanks in advance.

2
Have you tried with a return in front of the ternary? - Nam Bui
You do not return anything, that is the error - epascarello
export interface data { fields?: field[]; } isn't the ternary syntax wrong here ? ? - jarivak
@jarivak that is not a ternary typescriptlang.org/docs/handbook/… - epascarello

2 Answers

1
votes

You are missing the return statement in front of your ternary operator.

It should be:

return it.name===requiredName ? (
                    <Table>...</Table>
                  ) : (
                    null
                  )
1
votes

You have curly brackets in your arrow function, and therefore your ternary operator is executed as statement in the function body, but not returned.

This is what you currently have: (I just added the implicit return undefined to the function body.)

<TableCell>
  {props.fields.map((it) => {
    it.name===requiredName ? (<Table>...</Table>) : (null)
    return undefined
    }
  )} 
</TableCell>

The result of you map function is therefore an array with only undefined values in there.

You probably meant to do this (Note the absent curly brackets, which cause the arrow function to return the value of the ternary):

<TableCell>
  {props.fields.map((it) => 
    it.name===requiredName ? (<Table>...</Table>) : (null)
  )} 
</TableCell>