Warm tip: This article is reproduced from serverfault.com, please click

How to map object data or two arrays at the same time inside JSX

发布于 2020-11-28 08:31:19

I guess my problem is simple but i can't solve it. Could you help? I should make a simple graph bar data visualization based on JSON array data (a part of the JSON array is below):

{
      name: "R",
      year: 1956,
    },
    {
      name: "K",
      year: 1956,
    },
    {
      name: "P",
      year: 1982,
    },
    {
      name: "E",
      year: 1982,
    },
    {
      name: "S",
      year: 1992,
    }

The idea is to map <tr><div>{year}</div><div className="graph-bar" style={{ width: '${amount}px' * 10 }}></div><div>{amount}</div></tr> to each row to tell how many names were given in each year. So I reduced the JSON array to an object and calculated the amounts of the duplicate years:

Object { 1956: 7, 1982: 11, 1983: 2, 1989: 1, 1990: 2, 1991: 2, 1993: 2, 1994: 1, 1996: 1, 1998: 1, … }.

I have two questions:

  1. Can I map an object like above in JSX to the form given above?
  2. How can I use a multiplier (10 in this case) in inline CSS? This is not working: style={{ width: '${amount}px' * 10 }}. I have replaced backticks inside the inline style because I could not get them work here. Without the multiplier the backtick width is working. I have tried also calc() but it is not working.

As a plan B I have also made two simple arrays:

years = [ 1956, 1982, 1983, 1989, 1990, 1991, 1993, 1994, 1996, 1998, … ]

amount = [ 7, 11, 2, 1, 2, 2, 2, 1, 1, 1, … ]

If it is impossible map an object how can I map two arrays at the same time or is it possible?

Questioner
goduno
Viewed
0
Zodsmar 2020-11-28 16:59:54

With what you provided code wise it is hard to really determine exactly what you are going for but to map key value pairs you can use this:

for (const [key, value] of Object.entries(obj)) {
}

then use your key value as you would like.

For number 2:

style={{width: `${amount * 10}px`}}