我得到的响应字符串如下所示。
var txtResponse = "{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}";
需要将其放在html下拉列表中,并通过java脚本将Text指定为每个员工的"Given Name",将value指定为"Employee Number"。
我已经用它来为其他数组分配要下拉的值。
var select = document.getElementById("selectelement");
var optionContent = document.createElement("option");
optionContent.textContent = "";
optionContent.value = "";
select.appendChild(optionContent);
你能帮我通过循环从上面的响应中分配"textContent"one_answers"value"吗。
您可以迭代json对象中的所有键,如下所示,
var txtResponse = '{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
var jsonResponse = JSON.parse(txtResponse);
var select = document.getElementById("selectelement");
Object.keys(jsonResponse).forEach(key => {
var optionContent = document.createElement("option");
optionContent.textContent = jsonResponse[key]['Given Name'];
optionContent.value = jsonResponse[key]['Employee Number'];
select.appendChild(optionContent);
})
let res:any='{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
this.res=JSON.parse(this.res);
console.log('res==',this.res)
let select=document.getElementById("selectelement");
for(let el in this.res){
let optionContent=document.createElement("option");
optionContent.innerHTML=this.res[el]['Given Name'];
optionContent.value=this.res[el]['Employee Number'];
select.appendChild(optionContent);
}
<select id="selectelement"> </select>