How can I split the following string into an array that I can use to populate a html table

I have a string that looks like:

var str = '{ "abc": {
            "decline_reason": "Business rule switched off"
        },
        "def": {
            "decline_reason": "No response by interface"
        },
        "ghi": {
            "decline_reason": "Requested incorrect size" }';

I would like to split that string into an array that I can use to populate a table on a webpage. I intend to use the initial reference (‘abc’), with the reason (‘Business rule switched off’) on row 1, initial reference (‘def’), with the reason (‘No response by interface’) on row 2, etc…

I have tried regex to break it down, and I’ve managed to find one that removes quotes, but not to break the string down.

I intend to populate the table with code like:

<table id="declinesTable">
            <tr>
                <th onclick="sortTable(0)">Reference Code</th>
                <th>Decline Reason</th>
            </tr>
            <tr id="lender1">
                <td id="lender1"><script>document.getElementById("lender1").innerHTML = declines[0];</script>
                </td>
                <td id="declineReason1"><script>document.getElementById("declineReason1").innerHTML = declines[2];</script>
                </td>
            </tr>
        </table>

skipping out the value "decline_reason" from the table.

Any suggestions?

1 thought on “How can I split the following string into an array that I can use to populate a html table”

  1. Couple of things – your string is missing a final }. Not sure where you’re getting the string from, but it’s in JSON format, so use JSON.parse to get it into an object, then iterate over the object to do something with each individual nested object. I would strongly recommend using a library like jQuery to help you append it to the table. You can google and very quickly find out how to add jQuery to your project. See below.

    HTML

    <table id="declinesTable">
      <tr>
        <th>Reference Code</th>
        <th>Decline Reason</th>
      </tr>
    </table>
    

    Javascript (jQuery)

    var str = '{ "abc": {"decline_reason": "Business rule switched off"},"def": {"decline_reason": "No response by interface"},"ghi": {"decline_reason": "Requested incorrect size"}}'
    
    function stringParse(str){
      var items = JSON.parse(str);
      for(const [key, value] of Object.entries(items)) {
        $('#declinesTable').append(`<tr><td>${key}</td><td>${value.decline_reason}</td></tr>`)
      }
    }
    
    stringParse(str);
    
    Reply

Leave a Comment