Objects in any ECMAScript language (Javascript, Actionscript, Jscript, etc) are very powerful for – among other things – storing data. However, getting some information out of these objects can be a hassle sometimes.
I ran into this issue recently and wrote some cool little handlers for objects. The following methods can be used to iterate through an array manually. I wrote them for Actionscript, but they certainly work for Javascript – although I’d suggest one small modification (shown later).
Let’s get to the code.
In each of the “for in” loops below, I make sure to exclude any prototyped methods. If I don’t, they’ll show up in the loop – which can be pretty bad.
The ‘first’ method starts looping through the array, but returns the first item in the object as soon as it gets to it.
for (var s in this) if (!Object.prototype[s]) {
return s;
}
};
The ‘last’ method loops through the object, storing the current item in a variable. When it finishes the loop, it returns that variable – the last item in the object.
for (var s in this) if (!Object.prototype[s]) {
var l = s;
}
return l;
};
The ‘previous’ method loops through the object looking for the ’subject’ variable. If it matches the variable with the current item, it returns the previous item – set after the if statement below (in the previous time through the loop). If it never matches the variable or the previous item is never set, it will return the last item of the object.
for (var s in this) if (!Object.prototype[s]) {
if (s == subject && l !== undefined) {
return l;
}
var l = s;
}
return this.last();
};
The ‘next’ method loops through the object looking for the ’subject’ variable, as well. However, when it matches the variable it sets a ‘found’ flag. The next time through the loop, the current item will be returned. If it never matches the variable or the matched item is the last in the object, the first item will be returned.
var f = false;
for (var s in this) if (!Object.prototype[s]) {
if (f) {
return s;
}
if (s == subject) {
f = true;
}
}
return this.first();
};
So let’s do some examples. My test object has 3 items – one of which contains an array:
apple : [
'fuji',
'gala',
'red delicious'
],
banana : 'chiquita',
orange : 'navel'
};
myObject.first(); // returns 'apple'
myObject.last(); // returns 'orange'
myObject.previous('apple'); // returns 'orange'
myObject.next('apple'); // returns 'banana'
myObject.next('banana'); // returns 'orange'
myObject.next('orange'); // returns 'apple'
Simple as that.
The one change that I would recommend looking into for Javascript is better checking for the “for in” loops.
Instead of:
The hasOwnProperty property is recommended:
Good, I resolve this problem this night!!!
But I have always a recurent problem, how iterate on object like {}, builted WITH any properties as {} ?
var Obj = {
display:true,
infos:{
name:’Mine’,
address: ‘mine@me.net’,
others:{
again:false,
alast:’acidgreen’
}
}
}
You see that !
Thanks for your job.