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
the json that I returned is of this type
{
"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
We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.
The short answer: Yes but is not recommended.
We can use the JSON. stringify method to convert a plain JavaScript object into a string. This lets us check all the properties at once instead of hard coding the check as we did in the previous example. to remove the duplicate item by using JSON.
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]);
}
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?
Use a for in
loop
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>
it is too easy to use a for
loop
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With