Question

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.

Was it helpful?

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

OTHER TIPS

Why not using the plain old "for-in" structure ? Sometimes there's just no need of jQuery... This is more straight forward, more optimized : no function call, no tests with "if isObj thing", and it's maybe 2 or 3 lines of code...

var value;
for (var key in object)
{
  value = object[key];
  console.log(key, '=', value); //and voila !
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top