I\'m trying to take some data from an existing object and group it into a new one. The problem I am having is checking if the object key exists so I can either create a new
ExampleArray
[0] => siteoverlay
[1] => overlaycenter
[2] => someelementid
extend prototype if you want,(function here with while loop which is much faster than for in):
if (!('getKey' in Object.prototype)) {
Object.prototype.getKey = function(obj) {
var i=this.length;
while(i--)
{ if(this[i]===obj)
{return i;}
return;
}
};
}
then you can use:
alert(exampleArray.getKey("overlaycenter"));
returns: 1
also with prototype extension:
if(!('array_flip' in Array.prototype)){
Array.prototype.array_flip=function(array) {
tmp_ar={}; var i = this.length;
while(i--)
{ if ( this.hasOwnProperty( i ) )
{ tmp_ar[this[i]]=i; }
} return tmp_ar;
};
}
and then you can use:
alert(exampleArray.array_flip(exampleArray['someelementid']);
returns: 2
found out without prototype addition it is also functional
and eventually better for compatible scripting as everyone says not to extend the prototype...and so,...yes, if you want to use it with an easy 1 liner then you can use:
function array_flip( array )
{ tmp_ar={}; var i = array.length;
while(i--)
{ if ( array.hasOwnProperty( i ) )
{ tmp_ar[array[i]]=i; }
} return tmp_ar;
}
And
alert(array_flip(exampleArray)['siteoverlay']);
returns 0