Loop through an object or array

Loop through an object or array with jquery and javascript

HTML

<div id="object">

  <b>Results of Object:</b> </div>
<div id="array"><b>Results of Array:</b> </div>

JavaScript

var p = {
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
};

//Looping through json object with jquery
$.each(p, function(key, value) {
  console.log(key, value);
  document.getElementById('object').innerHTML += "Key " + key, "Value " + value;
});

//Looping through JSON object with plain javascript
for (var key in p) {
  if (p.hasOwnProperty(key)) {
    console.log(key + " -> " + p[key]);
  }
}



var array = [3, 2, 5, 1, 4];
var sorted = array.sort();

//Looping through sorted array
for (i = 0; i <= sorted.length; i++) {
  console.log(i);
  document.getElementById('array').innerHTML += i + " ";
}