Reputation: 21
What I'm trying to do is access object information that's inside of nested arrays. Something like:
<html>
<body>
<p id="demo"></p>
<script>
var people=[[[]]];
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
people[0][0][0].push(person);
document.getElementbyId("demo").innerHTML=people[0][0][0]person.lastName;
</script>
</body>
</html>
I know that to access element 0 of an array I'd use array[0]. I know that to access an attribute of an object I'd use object.attribute. But I can't seem to figure out how to access object attributes inside of an array. Can anyone help me, please?
Upvotes: 0
Views: 68
Reputation: 576
Correct code snippet below:
<html>
<head>
</head>
<body>
<p id="demo"></p>
<script>
var people=[[[]]];
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
people[0][0].push(person);
document.getElementById("demo").innerHTML = people[0][0][0]["firstName"];
</script>
</body>
</html>
Upvotes: 0
Reputation: 478
Your one array short for your sample code. Your code results in
var people=[[[]]];
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
people[0][0][0].push(person);
returns: TypeError: Cannot read property 'push' of undefined
you need to change
var people=[[[]]];
to
var people=[[[[]]]];
then you can just do
people[0][0][0][0].firstName
returns: "John"
Upvotes: 1