Search code examples
javascriptjsonhashtable

Getting multiple values out of a key in hashtable


I have an output from an API which gives multiple value want them to prettify as an indivual output in javascript

[
    {
        "key": "Time",
        "value": "\nTuesday, July 30, 2019 5:34:16 PM\nMonday, July 29, 2019 3:23:20 PM\nMonday, July 29, 2019 1:54:05 PM"
    }
]

Solution

  • I think this is what you're trying to do:

    const myDiv = document.getElementById("myDiv");
    const data = [
      {
        "key": "Time",
        "value": "\nTuesday, July 30, 2019 5:34:16 PM\nMonday, July 29, 2019 3:23:20 PM\nMonday, July 29, 2019 1:54:05 PM"
      }
    ];
    
    let items = data[0].value.split("\n"); // Splits value between "\n", making an array
    for (let item of items){ // Loops through items in the array, processing each in turn
      if(item.length > 0){ // Ignores items that are empty strings
        myDiv.innerHTML += item + "<br />"; // Adds the item and a line break to the div
      }
    }
    <div id= "myDiv"></div>