简体   繁体   English

映射中的动态键 Object

[英]dynamic key in mapping Object

hi i have an JSON object like this:嗨,我有一个 JSON object 像这样:

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.我想将对象的值插入到我的 div 中。 but i should write the Object key and my Number of Keys is Variable.但我应该写 Object 键,我的键数是可变的。 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>
                )) }

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.我假设你确实意识到这只会让你第一次进入每个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:为此,我建议将 json 的结构更改为如下所示:

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:修改 json 是不可能的,那么你可以用这个收集所有的Time键:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM