Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - 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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...