An API I’m connecting with, gives me back an object. One of its keys/properties is called “length” and this triggers some strange behaviour:
var obj = {"text1":{"index":0,"lengt":5}}; //modified key for testing
$.each(obj.text1,function(k,v){
console.log ('i: '+k+' v: '+v); });
i: index v: 0 //this is the result I'm looking for
i: lengt v: 5
var obj = {"text1":{"index":0,"length":5}}; //original object
i: 0 v: undefined // ????
i: 1 v: undefined
i: 2 v: undefined
i: 3 v: undefined
i: 4 v: undefined
I assume length is a reserved word, but that’s how the original object comes. What would be the best way to spot and skirt this issue?
Much thanks for any assistance.
This is a jquery “feature” ;-). According to the sources it treats a variable as an object if there is no
lengthproperty defined:https://github.com/jquery/jquery/blob/master/src/core.js#L589
And if
isObjisfalse– then see https://github.com/jquery/jquery/blob/master/src/core.js#L608As you can see it iterates over
ifrom0tolength