Search code examples
javascriptreactjsmappingshorthand

Shorthand check to map object field value and object key to Tsx element


Good evening.

I have an array of objects that I am trying to map to a tsx table element however I need to display the associated key of each field.

I have tried using Object.keys(item)[index] however I can't get it to return a value. Im looking for help with a short hand check, I have tried a few already but with no success.

                  {myArray.map((item: any) => (
                      <TableRow key={item.name}>
                        <TableCell >{item.name === row.name ? `${Object.keys(item)[2]}` && item.a || item.b || item.c || item.d || item.e : null}</TableCell>
                      </TableRow>
                    ))}

My array looks like the following:

[
  {
   a: 2,
   name: "obj1"
  },
  {
  b: 3,
  name: "obj2"
  },
  {
   c: 2,
   d: 5,
   name: "obj3"
  }
]

As I am mapping over the element it will return a table row foreach object, however im trying to get the row data to display as follows.

"a 2 ", // this will be the row data for obj1
"b 3 ",
"c 2, d 5"

TIA :)


Solution

  • It sounds like you need to iterate over the entries (except the name key), and join the keys and values together:

    <TableRow key={item.name}>
      <TableCell>{GetCell(item)}</TableCell>
    </TableRow>
    
    const GetCell = ({ name, ...rest }) => {
      return Object.entries(rest)
        .map(entry => entry.join(' '))
        .join(', ');
    };
    

    Or if you want a separate cell for each non-name key:

    {myArray.map(({ name, ...rest }) => (
      <TableRow key={name}>{
          Object.entries(rest)
            .map(entry => <TableCell>{entry.join(' ')}</TableCell>)
      }</TableRow>
    ))}