JavaScript function, which reads connections between objects

Posted by Nikita Sumeiko on Stack Overflow See other posts from Stack Overflow or by Nikita Sumeiko
Published on 2010-04-23T16:00:00Z Indexed on 2010/04/23 16:03 UTC
Read the original article Hit count: 263

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about literals