In this post, we will learn how to display all items or values in an array or an object using loop in jQuery. So how we can do this, we will learn in this post.

How To Display All Items Or Values In An Array Or An Object Using Loop In jQuery ?

Display All Items Or Values In An Array Or An Object Using Loop

To display all items or values in an array or object using loop, we use  jQuery.each()  or  $.each()  method. This method helps us to iterate over an array or loop through an array. This method is also used for object. This method internally use the  length  property of the passed array or object. If it has a property called  length  for example  array = ['length', 'length1'];  or  object = {"length":5}  then the function might not work properly.  

Display All Items Of An Array

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Display All Items Or Values In An Array Or An Object Using Loop In jQuery ?</title>
</head>
<body>

<div id="showResult"></div>

<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>

$(document).ready(function(){
// Array
var progLang = ["HTML", "CSS", "JavaScript", "PHP", "MySQL"];
$.each(progLang, function(index, lang){
$("#showResult").append(index + ": " + lang + '<br>');
});
});

</script>
</body>
</html> code-box

Display All Items Of An Object

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Display All Items Or Values In An Array Or An Object Using Loop In jQuery ?</title>
</head>
<body>

<div id="showResult"></div>

<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script>

$(document).ready(function(){
// Object
var langObject = {"One": "HTML", "Two" : "CSS", "Three": "JavaScript"};
$.each(langObject, function(key, value){
$("#showResult").append(key + ": " + value + '<br>');
});
});
</script>
</body>
</html> code-box


Summary

In this post we learned how to display all items or values in an array or an object using loop in jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.  

Post a Comment

Previous Post Next Post