[turboid] javascript solutions

Home     Contact     Search     About me
Syntax solutions
27 Dec 2011

Strange key names in for-in-loops

How to handle prototype manipulation problems

Adding properties and functions to object prototypes interferes with for-in-loops - seemingly wrong results are found while going through a new array. This is why one is often advised to keep away from object and array prototype manipulation. But there is a simple way to reduce the problems.

Perhaps you already happened to notice that going through the properties of an object or the elements of a (pseudo) associative array using the for-in-loop lets the script find strange keynames which you didn't expect to be part of your object. Those, most probably, are the names of prototypes which have been defined somewhere in this way:

Object.prototype.myFnc = function() {
	// [...]
}

// Or:

Array.prototype.myFnc = function(){
	// [...]
}

This can be very annoying, and it's not a convenient solution to check in each for-in-loop if the found key name is identical to one of the strange names in order to pay attention to it or not. But if you use the the free Turboid framework or copy the code at the end of this article you get a quite convenient solution which allows you to use for-in-loops almost as usually, without building in intricate filter queries.

So, instead of:

for(var key in myObj){ 
	// Do something
}

You write:

for(var key in myObj){ if(keyOk(key)){
	// Do something
}}

If you'd like to save some letters you can also write:

from(myObj, function(key){
	// Do something
});

However, if you want to build one loop into another, the from()-method is not the first option.

Try out the solutions mentioned above after copying the following code or downloading the Turboid framework:

function keyOk(key){
	if(!(key in Object.prototype) && !(key in Array.prototype) && key!="undefined")
		return 1;
	else
		return 0;
}

function from(list, fnc){
	for(var k in list){ if(keyOk(k)){
		fnc(k);
	}}
};
Enjoy!

Comments

Add comment:

Name: (required)
E-Mail: (required, remains invisible)
Website:
Comment:
Please check all (anti-spam):