I have a JSON String in this format:
我有这个格式的JSON字符串:
{
"supplier": {
"mov_10": "love actually",
"mov_1": "fare"
},
"quantity": 20,
"success": true,
"length":2
}
Now I want to create a select box below using the supplier
object (using both the keys and values), like this:
现在,我希望使用供应商对象(同时使用键和值)创建一个选择框,如下所示:
<select id="selectme">
<option id="mov_10">love actually</option>
<option id="mov_1">fare</option>
</select>
So how do I create it? I just want to know how to reach mov_10
and mov_1
in the object. Sorry for my bad English, but please help me.
那么我如何创建它呢?我只是想知道如何在对象中到达mov_10和mov_1。对不起,我的英语不好,但请帮助我。
Thanks.
谢谢。
2 个解决方案
#1
0
If I understood the question correctly, I think you might want to use something along this:
如果我正确地理解了这个问题,我想你可能想在这个问题上用点什么:
var jsonArray = ... ; // {"supplier": ... } (JS Object)
var supplierOptions = jsonArray.supplier;
// TODO: remember to set up selectme!
for(var optionId in supplierOptions) {
if(!supplierOptions.hasOwnProperty(optionId)) {
continue;
}
var optionValue = supplierOptions[optionId];
// operate with name and value here (append to select ie.)
$("#selectme").append('<option id="' + optionId + '">' + optionValue + '</option>');
}
The code probably could use some cleaning up. Hopefully it conveys the basic idea, though.
代码可能需要一些清理。希望它传达了基本的思想。
#2
2
Use the for...in statement to iterate over keys:
使用……在语句中迭代键:
for ( var k in someObject.supplier ) {
someOption.value = k;
someOption.text = someObject.supplier[ k ];
}
#1
0
If I understood the question correctly, I think you might want to use something along this:
如果我正确地理解了这个问题,我想你可能想在这个问题上用点什么:
var jsonArray = ... ; // {"supplier": ... } (JS Object)
var supplierOptions = jsonArray.supplier;
// TODO: remember to set up selectme!
for(var optionId in supplierOptions) {
if(!supplierOptions.hasOwnProperty(optionId)) {
continue;
}
var optionValue = supplierOptions[optionId];
// operate with name and value here (append to select ie.)
$("#selectme").append('<option id="' + optionId + '">' + optionValue + '</option>');
}
The code probably could use some cleaning up. Hopefully it conveys the basic idea, though.
代码可能需要一些清理。希望它传达了基本的思想。
#2
2
Use the for...in statement to iterate over keys:
使用……在语句中迭代键:
for ( var k in someObject.supplier ) {
someOption.value = k;
someOption.text = someObject.supplier[ k ];
}