Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript For each json [duplicate]

Tags:

javascript

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

like image 250
Kevin Avatar asked Mar 31 '15 10:03

Kevin


People also ask

Can JSON have duplicate values?

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.

Can JSON have repeated keys?

The short answer: Yes but is not recommended.

Does JSON Stringify remove duplicates?

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.


4 Answers

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]);
}
like image 55
jmgross Avatar answered Oct 22 '22 20:10

jmgross


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?

like image 24
Beri Avatar answered Oct 22 '22 19:10

Beri


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>
like image 21
Juan Mendes Avatar answered Oct 22 '22 18:10

Juan Mendes


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]);
}
like image 1
Khalid Avatar answered Oct 22 '22 18:10

Khalid