Javascript 对于每个 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29366137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript For each json
提问by Kevin
I'm making a call via ajax javascript to a page (ASP) that returns a json with which I would then go to a select value
我正在通过 ajax javascript 调用一个页面 (ASP),该页面返回一个 json,然后我将转到一个选择值
the json that I returned is of this type
我返回的 json 就是这种类型
{
"options": {
"1": "All locations",
"2": "Egypt",
"3": "El Alamein",
"4": "Marsa matrouh",
"5": "Sharm el sheikh "
}
}
or
或者
{
"options": {
"1": "All locations",
"2": "Abu dhabi",
"3": "Dubai"
}
}
I don't know the length and the elements that are contained then I would make a loop that allows me to extract the values which then will insert the value and label
我不知道包含的长度和元素,然后我会做一个循环,允许我提取值,然后将插入值和标签
I'm looking at the net but the examples shown are always with the field name to be recalled that I could not learn about not knowing the length
我正在查看网络,但显示的示例总是带有要回忆的字段名称,我无法了解不知道长度
could someone kindly show me how this cycling json
有人可以告诉我这个骑自行车的json
回答by jmgross
var obj = {"options": {"1": "All locations", "2": "Egypt", "3": "El Alamein", "4": "Marsa matrouh", "5": "Sharm el sheikh "}}
for(var item in obj.options) {
console.log(obj.options[item]);
}
回答by Beri
For iterating over dictionary you can sue this:
为了迭代字典,你可以起诉这个:
var dict = obj.options;
Object.keys(dict).forEach(function(key) {
console.log(key +': '+ dict[key]);
});
to know only the length you can simply use:
只知道你可以简单地使用的长度:
Object.keys(dict).length;
I think that here you can find more answers: How do I loop through or enumerate a JavaScript object?
我认为在这里您可以找到更多答案: How do I loop through or enumerate a JavaScript object?
回答by Juan Mendes
Use a for in
loop
使用for in
循环
var obj = {"options": {"1": "All locations", "2": "Egypt", "3": "El Alamein", "4": "Marsa matrouh", "5": "Sharm el sheikh "}};
var ul = document.querySelector('ul');
for (var index in obj.options) {
var li = document.createElement('li')
ul.appendChild(li);
li.innerHTML = index + ": " + obj.options[index];
}
<ul ></ul>
回答by Khalid
it is too easy to use a for
loop
使用for
循环太容易了
var obj = {"options": {"1": "All locations", "2": "Egypt", "3": "El Alamein", "4": "Marsa matrouh", "5": "Sharm el sheikh "}};
for(key in obj.options) {
console.log(key, obj.options[key]);
}