在 Javascript 中创建动态下拉菜单

Create the Dynamic dropdown in Javascript

有人指导我,如何在 javascript 中使用下面的 array/JSON 创建动态下拉列表?

 [
    {
      "1": "001",
      "2": "002",
      "3": "003"
    }
];

What I have done :

 let text = "<select class='form-control'><option value=''>All</option>";
                        
                        var array = [
                            {
                                "1": "001",
                                "2": "002",
                                "3": "003"
                            }
                        ];
                       
                        for (var i = 0; i < array.length; i++) {
                            // POPULATE SELECT ELEMENT WITH JSON.
                            text += '<option value=' + array[i]["1"] + '>'+ array[i]["1"] +'</option>';
                        }

使用Object.entries()读取对象中的字段。

var array = [
  {
    "1": "001",
    "2": "002",
    "3": "003"
  }
];
var x = document.createElement("SELECT");
x.setAttribute("id", "mySelect");
document.body.appendChild(x);

for (const [key, value] of Object.entries(array[0])) {
  var z = document.createElement("option");
  z.setAttribute("value", key);
  var t = document.createTextNode(value);
  z.appendChild(t);
  document.getElementById("mySelect").appendChild(z);
}       

正在使用 JavaScript 创建 Select 元素:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to create a SELECT and an OPTION element.</p>

<button onclick="myFunction()">Try it</button>

<script>
const customItems = [
    {
      "1": "001",
      "2": "002",
      "3": "003"
    }
];

function myFunction() {
  const x = document.createElement("SELECT");
  x.setAttribute("id", "mySelect");
  document.body.appendChild(x);
  
  for (let i = 0; i < customItems.length; i++) {
    for (let key in customItems[i]) {
        const z = document.createElement("option");
        z.setAttribute("value", customItems[i][key]);
        const t = document.createTextNode(customItems[i][key]);
        z.appendChild(t);
        document.getElementById("mySelect").appendChild(z);
    }
    
  }
}
</script>

</body>
</html>