views:

59

answers:

2

I have a JavaScript literal:

var members = {
    "mother": {
        "name" : "Mary",
        "age" : "48",
        "connection": {
            "brother" : "sun"
        }
    },
    "father": {
        "name" : "Bill",
        "age" : "50"
    },
    "brother": {
        "name" : "Alex",
        "age" : "28"
    }
}

Than I have a function, which should read connections from the literal above. It looks like this:

 function findRelations(members){
    var wires = new Array();
    var count = 0;
    for (n = 0; n < members.length; n++){
         alert(members.length); // this alert is undefined
        if (members[n].connection){
            for (i = 0; i < members[n].connection[0].length; i++){
                var mw = new Array();
                var destination = 0;
                for (m = 0; m < members.length; m ++){
                    if (members[m] == members[n].connection[0]){
                        destination = m;
                        mw = [n, destination];
                        wires [count] = mw;
                        count++;
                    }
                }
            }
        }
    }
    return wires;
 }

However, when I run this function, I get nothing. And the first alert, which is placed inside the function shows 'undefined' at all.

findRelations(members);
alert("Found " + wires.length + " connections");

I guess that's because of JavaScript literal. Could you suggest how to change a function or perhaps to change litteral to JSON array to get it work?! And at the end to get 'm' and 'n' values as numbers.

+1  A: 

What is a 'literal'? I guess you mean 'an object created using the literal notation'.

Only Array's (and strings) have a length property, what you want is to loop through the properties

for (var prop in members) {
    if (members.hasOwnProperty(prop)) {
          alert("members has property " + prop);
    }
}

This should get you on the right path as its not easy to follow the rest of the logic

Sean Kinsey
+1 This should indeed get him on the right path. Re *"What is a 'literal'?"* That's perfectly standard terminology, we talk about string literals ("hi there") and numeric literals, rather than "strings created using literal notation." :-) What he has there is an object literal.
T.J. Crowder
That is true, but stating only that it is a 'literal' is not specific enough as you your self stated, we have string, numeric, object and array literals. My point was only that a literal on its own is not a defined type.
Sean Kinsey
A: 

The alert gives you "undefined" because your function seems to be expecting an array whereas your "members" variable is an Object.

the "length" property is not defined on an object. So,

var a = {
    name:'test',
    age:56
};
console.log(a.length);  //undefined

The same is the reason for getting no response as well.

Rajat