JavaScript Dictionary of Arrays Example 2021



This post shows a quick JavaScript dictionary of arrays example. It also shows one way to iterate over a dictionary. It's important to note that it's for demonstration purposes only. You should always be careful to properly handle XSS, performance, and other items in your own production usage.

Example

<html>
<head>
    <script type="text/javascript">
        function handleBodyOnLoad() {
            const items = {
                "Item One Coordinates": [
                    { "x": "10", "y": "20" },
                    { "x": "30", "y": "40" },
                    { "x": "50", "y": "60" }
                ],
                "Item Two Coordinates": [
                    { "x": "70", "y": "80" }
                ]
            };

            const exampleOutputDiv = document.getElementById("exampleOutput");
            var listItemsOutputStr = "";

            for (const [key, item] of Object.entries(items)) {
                listItemsOutputStr += "<div>" + key + ":<ul>";

                for (const [index, coordinates] of Object.entries(item)) {
                    listItemsOutputStr += "<li>" + "X:" + coordinates.x + ", Y:" + coordinates.y + "</li>";
                }
                listItemsOutputStr += "</ul></div>";
            }

            exampleOutputDiv.innerHTML = listItemsOutputStr;
        }
    </script>
</head>
<body onload="handleBodyOnLoad()">
    <div id="exampleOutput" />
</body>
</html>

Output

Item One Coordinates:
  • X:10, Y:20
  • X:30, Y:40
  • X:50, Y:60
Item Two Coordinates:
  • X:70, Y:80