Home > database >  Parse JSON Results into Multiple HTML columns Using JQuery
Parse JSON Results into Multiple HTML columns Using JQuery

Time:04-04

I am working with an API and would like to extract API Results into an HTML table columns with X number of rows. This an issue with JQuery looping, do not know how to do it. Thanks in Advance!

/////JSON SAMPLE/////
{
  "123SC": [{
      "name": "First",
      "Custnumber": "123SC"
    },
    {
      "name": "Fourth",
      "Custnumber": "123SC"
    }
  ],
  "67BC": [{
    "name": "Second",
    "Custnumber": "67BC"
  }],
  "99ABC": [{
    "name": "Third",
    "Custnumber": "99ABC"
  }]
}
///////// END JSON //////

<table style="width:100%" border="2">
  <tr>
    <td>First</td>
    <td>Forth</td>
    <td>Second</td>
    <td>Third</td>
  </tr>
  <tr>
    <td>123SC</td>
    <td>123SC</td>
    <td>67BC</td>
    <td>99ABC</td>
  </tr>
</table>

CodePudding user response:

Try this:

    let json = {
        "123SC": [{
            "name": "First",
            "Custnumber": "123SC"
        },
        {
            "name": "Fourth",
            "Custnumber": "123SC"
        }
        ],
        "67BC": [{
            "name": "Second",
            "Custnumber": "67BC"
        }],
        "99ABC": [{
            "name": "Third",
            "Custnumber": "99ABC"
        }]
    };

    let arrays = [];
    for (const i in json) arrays = [...arrays, ...json[i]];



    let names = '<tr>';
    let Custnumber = '<tr>';
    for (let i = 0; i < arrays.length; i  ) {
        names  = `<td>${arrays[i].name}</td>`;
        Custnumber  = `<td>${arrays[i].Custnumber}</td>`;
    }
    names  = '</tr>';
    Custnumber  = '</tr>';
    let html = `<table style="width:100%" border="2">${names   Custnumber}</table>`;
    document.write(html);

  • Related