-2

I am new to Javascript and I was trying to display an array of objects. I could not really make it happen. Because the number of objects in the array is more than one and each object has 2 attributes. eg

var person = {
    firstName : "John",
    lastName  : "Doe",
    age       : 50,
    eyeColor  : "blue"
};

var person1 = {
    firstName : "Ben",
    lastName  : "",
    age       : 44,
    eyeColor  : "brown"
};
var people = [];

people.push(person);
people.push(person1);

Now, if i want to print the "firstname" then what should i do for the script and the body of the html file? Thanks in advance

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Ashrar
  • 1
  • 4
    Try to use Google. It's a tool to find stuff around the Internet(Internet is a network of computers). – GuyT Oct 02 '14 at 09:15

3 Answers3

2

You access the attributes of an object like person.firstName person.lastName and so on.

Now considering they're in an array, you need to first write a loop till the array's length (Number of persons)

for(var i=0; i< people.length; i++)

Inside this loop, you can access the persons and their properties like:

people[i].firstName

So your complete working code should be like:

var person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" };

var person1 = { firstName : "Ben", lastName : "", age : 44, eyeColor : "brown" }; 
var people = [];

people.push(person); people.push(person1);


for(var i=0; i<people.length; i++){
  document.write(people[i].firstName + "<br>");
  document.write(people[i].lastName + "<br>");
  document.write(people[i].age + "<br>");
  document.write(people[i].eyeColor + "<br>");
}

im using document.write to display the result and <br> is used for the newline.

Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43
0

For inserting the values in a div you can use innerHTML like this http://jsfiddle.net/w5b5drnr/1/ And to make the javascript code work you should insert it at the bottom of the page after all the content is ready :)

var people = [];

var result = document.getElementById('result');
var person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" };
var person1 = { firstName : "Ben", lastName : "", age : 44, eyeColor : "brown" }; 

people.push(person); 
people.push(person1);

for(var i =0; i< people.length; i++){
    result.innerHTML += people[i].firstName + '<br/>';
}
Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34
-1

Following code will print car 1

<p id="demo"></p>

<script>
var cars = ["Car1", "Car2", "Car3"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>
Boldbayar
  • 862
  • 1
  • 9
  • 22