js / jquery: issue with object key called "length"

javascript, jquery, key, object, reserved-words

Solution

This is a jquery "feature" ;-). According to the sources it treats a variable as an object if there is no `length` property defined:

https://github.com/jquery/jquery/blob/master/src/core.js#L589

var name,
    i = 0,
    length = obj.length,
    isObj = length === undefined || jQuery.isFunction( obj );
      ^---------

And if `isObj` is `false` - then see https://github.com/jquery/jquery/blob/master/src/core.js#L608

if ( isObj ) {
    // not your case, ommitted
} else {
    for ( ; i < length; ) {
        if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
            break;
        }
    }
}

As you can see it iterates over `i` from `0` to `length`

Problem

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.

Original source