gpt4 book ai didi

javascript - 从 JSON 对象创建选择表单属性

转载 作者:行者123 更新时间:2023-11-30 21:18:14 25 4
gpt4 key购买 nike

我正在尝试从我的 json 对象中的键和值构建一个选择下拉列表,但我无法将键值对放在一起,我只成功地获取了键名本身。以下是我到目前为止能够完成的内容。

这就是我希望选择的选项的样子:

 <select id="optSelect">
<option value="key1">value1</option> <!-- should come from name1 -->
<option value="key1">value2</option> <!-- should come from name2 -->
</select>

我是否需要创建另一个数组来保存每个键的值,然后在构建选择选项时进行相应引用,或者是否有其他方式或方法?

    var someObject = {
"Name1": {
"key1": "value1",
},
"Name2": {
"key1": "value2",
}
}


var objArray = [];

for(var i in someObject){
var key = someObject[i];
for(var x in key1){
var nextKey = x;
var nextVal = key1[x];
someObject.push(nextKey);
}
}

var optionSelect = document.getElementById("optSelect"),
selectList = document.createElement("select");

selectList.id = "mySelect";
optionSelect.appendChild(selectList);

for (var i = 0; i < objArray.length; i++) {
var option = document.createElement("option");
option.value = objArray[i]; // need to get key1 in here for each value in someObject
option.text = objArray[i]; // need to get value 1 or 2 etc in here for each value name in someObject
selectList.appendChild(option);
}

最佳答案

for(var x in key1){,此处key1未定义,您需要更正。然后在您的 objArray 中,您需要保存所有键值对,仅推送其中的值会使以后难以使用。你可以在 objArray 中推送对象,还有你为什么要创建 selectList 然后将它附加到 optionSelect,你可以直接将你的选项附加到 optionSelect,如下所示:

 var someObject = {
"Name1": {
"key1": "value1",
},
"Name2": {
"key1": "value2",
}
}


var objArray = [];

for(var i in someObject){
var key1 = someObject[i];
for(var x in key1){
objArray.push({'key' : x, 'val' : key1[x]});
}
}

var optionSelect = document.getElementById("optSelect"),
selectList = document.createElement("select");

selectList.id = "mySelect";
optionSelect.appendChild(selectList);

for (var i = 0; i < objArray.length; i++) {
var option = document.createElement("option");

option.value = objArray[i].key; // need to get key1 in here for each value in someObject
option.text = objArray[i].val; // need to get value 1 or 2 etc in here for each value name in someObject
optionSelect.appendChild(option);
}
<select id="optSelect">

</select>

关于javascript - 从 JSON 对象创建选择表单属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com