5

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

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
Kevin
  • 415
  • 3
  • 8
  • 21

4 Answers4

15
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]);
}
jmgross
  • 2,306
  • 1
  • 20
  • 24
5

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?

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57
1

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>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

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]);
}
Khalid
  • 4,730
  • 5
  • 27
  • 50