dynamic key in mapping Object

Viewed 29

hi i have an JSON object like this :

WorkTime=[{
      "Day": "6",
      "Time1": "8 : 00 - 9 : 00",
      "Time2": "9 : 00 - 10 : 00",
      "Time3": "10 : 00 - 11 : 00",
      "Time4": "11 : 00 - 12 : 00",
      "Time5": "12 : 00 - 13 : 00",
      "Time6": "13 : 00 - 14 : 00",
      "Time7": "17 : 00 - 18 : 00",
      "Time8": "18 : 00 - 19 : 00",
      "Time9": "19 : 00 - 20 : 00",
      "id": 1
    },
    {
      "Day": "0",
      "Time1": "8 : 00 - 9 : 00",
      "Time2": "9 : 00 - 10 : 00",
      "Time3": "10 : 00 - 11 : 00",
      "Time4": "11 : 00 - 12 : 00",
      "Time5": "12 : 00 - 13 : 00",
      "Time6": "13 : 00 - 14 : 00",
      "id": 2
    },]

and i want insert object's Value into My div . but i should write the Object key and my Number of Keys is Variable. for this i decide to use index and dynamic call Keys but i don't know anything about its Syntax . What I want to do is almost like this :

 {
                   WorkTime.map((item, index) => (
                  <div key={index} id={`Ticket${item.Day}Box`} className="bg-gray-50 p-3 w-11/12
                   rounded-t-xl mx-auto" style={{ display: "none" }}>
                    {item.Time{index+1}} 
                  </div>
                )) }

instead Of Call Keys Like This :

WorkTime.map((item, index) => (
                  <div key={index} id={`Ticket${item.Day}Box`} className="bg-gray-50 p-3 w-11/12
                   rounded-t-xl mx-auto" style={{ display: "none" }}>
                    {item.Time1} 
                  </div>
                )) }

1 Answers

To answer your question, you can use the brackets syntax and string interpolation to get what you want:

item[`Time${index + 1}`]

I'm assuming you do realize that this will only give you the first time entry from every WorkTime object. If you want to show all the time entries, you'll have to iterate over them separately. For this I'd recommend changing the structure of your json to something like this:

WorkTime = [{
  id: 0, // whatever
  day: "day string",
  times: ["time 1", "time 2"] // etc
}]

It modifying json is not possible, then you can collect all the Time keys with this:

Object.keys(item).filter(k => k.match(/Time\d/))
Related