View Full Version : Accessing an object within an array nested within another object.

10-05-2011, 04:31 AM
I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)...

Problem is I'm not sure how to properly access those properties... see below please.


//This is an example of a problem im having in my own code...
//I want to access the name of the object within the links array wintin the object...

var objA = {name: "Object A", links: [objB, objC]};
var objB = {name: "Object B", links: [objC, objD, objE]};
var objC = {name: "Object C", links: [objB]};
var objD = {name: "Object D", links: [objE]};
var objE = {name: "Object E", links: [objD]};

//ex: I want to access the name of Object A's first link...


I'm hoping to get "Object B"...
But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object.
Is there another way around this? Any thoughts are appreciated.

10-05-2011, 05:02 AM
Uh well , probabley not what
you are after but it gives the
results you wanted that is ,
"Object B"...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="daveyerwin">
var objA = {name: "Object A", links: ['objB', 'objC']};
var objB = {name: "Object B", links: ['objC', 'objD', 'objE']};
var objC = {name: "Object C", links: ['objB']};
var objD = {name: "Object D", links: ['objE']};
var objE = {name: "Object E", links: ['objD']};




Old Pedant
10-05-2011, 05:41 AM
I assume you are aware that if you simply changed the order of your code it would work:

var objB = {name: "Object B", links: [objC, objD, objE]};
var objA = {name: "Object A", links: [objB, objC]};

But of course, that doesn't help get links[1] or links[2] and there's no ordering of code that works for objD and objE.

But you know, you could always do this:

var objA = {name: "Object A" };
var objB = {name: "Object B" };
var objC = {name: "Object C" };
var objD = {name: "Object D" };
var objE = {name: "Object E" };
objA.links = [objB, objC];
objB.links = [objC, objD, objE];
objC.links = [objB];
objD.links = [objE];
objE.links = [objD];

document.write( objA.links[0].name );

It's not as neat and clean, but...

10-05-2011, 01:46 PM
Thank you for your replies!

I think I'll have to change my code to add the links property after and all should work well. Thanks for your time with this!!