Object values undefined and NaN

Go To StackoverFlow.com

-1

I have a function which creates an object of values, but im getting this in my console log:

 x: Array[4]
 0: undefined
 1: NaN
 2: undefined
 3: NaN
 length: 4
 y: Array[4]
 0: undefined
 1: NaN
 2: undefined
 3: NaN
 length: 4

The function loops on an object created from a PHP file which was json encoded:

 var sdata = {"4":{"7":["1","7","2","2"]},"3":{"3":["2","8","1","1"]}};

My function is:

function populate_collisions(){
gcollision = { 
    x: [],
    y: []    
    };

for(var key in sdata){
    gcollision.x.push( sdata[key][0] );
    gcollision.x.push( sdata[key][0] + (sdata[key][2]-1) );
    gcollision.y.push( sdata[key][1] );
    gcollision.y.push( sdata[key][1] + (sdata[key][3]-1) );
}
console.log(gcollision);
}

I'm curious to know why im getting undefined and NaN? And how do i solve the problem?

2012-04-04 01:11
by Sir


2

your "object/array hybrid" is 3D (3-levels deep).

var sdata = {
    "4": {                       
        "7": ["1", "7", "2", "2"]
    },
    "3": {
        "3": ["2", "8", "1", "1"]
    }
};

in the first item, you got key "4", then under it, a key "7" and after that, your array. you lacked an additional loop:

function populate_collisions() {
    gcollision = {
        x: [],
        y: []
    };

    for (var key in sdata) {
        for (var keyTwo in sdata[key]) {
            gcollision.x.push(sdata[key][keyTwo][0]);
            gcollision.x.push(sdata[key][keyTwo][0] + (sdata[key][keyTwo][2] - 1));
            gcollision.y.push(sdata[key][keyTwo][1]);
            gcollision.y.push(sdata[key][keyTwo][1] + (sdata[key][keyTwo][3] - 1));

        }
    }
    console.log(gcollision);
}
2012-04-04 01:23
by Joseph
Hmm ok it worked but its adding the values together like strings rather than a mathematical calculation = - Sir 2012-04-04 01:44
then this post might help you, or if possible, remove the quotes surrounding your values in the array. that will turn them to numbers - Joseph 2012-04-04 01:47
I can't remove the quotes they are made in PHP i think it defaults to string on json_encode. I shall try a pass int - Sir 2012-04-04 01:48
or, use a JSON parser. some modern browsers have it built in - Joseph 2012-04-04 01:50
Hmm the result of gcollision is not what i was expecting =/ thinking i might have approached this wrong = - Sir 2012-04-04 02:01
Ads