Js / jquery: problem with object key called length,

The API I'm contacting returns an object to me. One of its keys / properties is called "length", and this causes strange behavior:

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 that length is a reserved word, but this is how the original object happens. What would be the best way to identify and solve this problem?

Thanks so much for any help.

+4
source share
2 answers

This is jquery "feature" ;-). According to sources, it treats the variable as an object if the length property is not 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 - 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

+4
source

Why not use the plain old "inline" structure? Sometimes there is simply no need for jQuery ... This is more straightforward, optimized: there is no function call, no tests with the "if isObj thing" and, possibly, 2 or 3 lines of code ...

 var value; for (var key in object) { value = object[key]; console.log(key, '=', value); //and voila ! } 
+1
source

All Articles