-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?

Sir
  • 8,135
  • 17
  • 83
  • 146

1 Answers1

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);
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Hmm ok it worked but its adding the values together like strings rather than a mathematical calculation =/ – Sir Apr 04 '12 at 01:44
  • then [this post](http://stackoverflow.com/a/1133814/575527) might help you, or *if possible*, remove the quotes surrounding your values in the array. that will turn them to numbers. – Joseph Apr 04 '12 at 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 Apr 04 '12 at 01:48
  • or, use a [JSON parser](https://github.com/douglascrockford/JSON-js). some [modern browsers](http://caniuse.com/json) have it built in. – Joseph Apr 04 '12 at 01:50
  • Hmm the result of gcollision is not what i was expecting =/ thinking i might have approached this wrong =/ – Sir Apr 04 '12 at 02:01