padma2129
padma2129

Reputation: 49

Not able to traverse array of objects in javascript.Got output for first element only

var persons = new Array();
var person = {
  firstname: "Padma",
  Id: 1,
  Country: "India"
};
persons.push(person);
persons.push([person = {
  firstname: "Balaji",
  Id: 3,
  Country: "India"
}]);
persons.push([person = {
  firstname: "Sivasree",
  Id: 2,
  Country: "India"
}]);
document.getElementById("demo").innerHTML = persons.length;
$.each(persons, function(key, value) {
  console.log(value.firstname + " " + value.Country + "\n");
});
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>


  <h2>JavaScript Objects</h2>
  <p>JavaScript uses names to access object properties.</p>
  <p id="demo">


</body>

</html>

Upvotes: 1

Views: 49

Answers (1)

Swati
Swati

Reputation: 28522

In your current code you are passing JSON Array inside JSON Object and that JSON Object inside outer JSON Array but your structure should look like [{},{}..] so you can just use persons.push({.. to push object inside main array.

Demo Code:

var persons = new Array();
var person = {
  firstname: "Padma",
  Id: 1,
  Country: "India"
};
persons.push(person);
persons.push({
  firstname: "Balaji",
  Id: 3,
  Country: "India"
}); //this is same as above pushing json object inside json array
persons.push({
  firstname: "Sivasree",
  Id: 2,
  Country: "India"
});
document.getElementById("demo").innerHTML = persons.length;
$.each(persons, function(key, value) {
  console.log(value.firstname + " " + value.Country + "\n");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>

Upvotes: 1

Related Questions