0

Sample of JSON entries:

 {
  "id": 6,
  "count": 6,
  "title": "Famous football teams from England?",
  "content_00": "On the Premier League:",
  "content_01": "1) Manchester United,",
  "content_02": "2) Manchester City,",
  "content_03": "3) Liverpool,",
  "content_04": "4) Tottenham Hotspurs.",
  "content_05": "These are just a few, there are 20, etc."
 },
 {
  "id": 6,
  "count": 3,
  "title": "Famous Golfers?",
  "content_00": "Tiger Woods",
  "content_01": "Rory McIlroy,",
  "content_02": "Justin Thomas,",
 }

and so on. As you can see, some entries may have 6 "contents", some 3, some 1. So what I want, which I can do in PHP, but my code right now is REACT, is to have a loop, something like this. By the way, I am currently using map to go through these entries.

For example:

for (let i = 0; i < mapName.count; i++)
 {
  if (i < 10)
    variableName = "content" + "0" + i;
  else
    variableName = "content" + i;
  <dev>
    <p>{mapDetail.variableName}</p>
  </dev>
 }

As one goes through the loop, which can be only one variable of more needed, the value of the "variableName" would change as follows if we had 4 items in the JSON file:

variableName = "content_00"
variableName = "content_01"
variableName = "content_02"
variableName = "content_03"

Where the "00", "01", "02" & "03" were appended to "content_" in order to read the contents on each of the entries in the JSON file.

I would get "content_01" though "content_09" from the 1st "if", and then "content_11" etc. after that. The loop would allow me to complete the variable name.

And so forth...I don't have the full code here, of course, but I hope I am getting the idea across.

lifeisfoo
  • 15,478
  • 6
  • 74
  • 115
Manny
  • 81
  • 2
  • 7
  • Please try to use

    {mapDetail[variableName]}

    –  Dec 28 '20 at 00:09
  • I am new to REACT and Javasript. I believe that I am using what you are suggesting. I am reading a JSON file in order to get the information I need, but each entry is unique in the sense that it may have just the title and one content (content_00), or many more. The count value would allow me to create as many "content_" variables as I need, and that is what I am trying to accomplish. – Manny Dec 28 '20 at 14:34
  • I can send you answer but I can not type my answer.. How will I send you my result? –  Dec 28 '20 at 14:49
  • for (let i = 0; i < mapName.count; i++) { if (i < 10) variableName = "content_" + "0" + i; else variableName = "content_" + i;

    {mapDetail[variableName]}

    }
    –  Dec 28 '20 at 14:52
  • Hello Artem, Here is the code where I want to insert the loop:
    {FAQdata.map((faqDetail, index)=>{ return

    {faqDetail.title}

    {faqDetail.content_00}
    {faqDetail.content_01}
    {faqDetail.content_02}

    })}
    How do I insert the loop without getting errors? Thank you very much for your help.
    – Manny Dec 28 '20 at 16:54

0 Answers0