Working with objects in Javascript is a blast. The Object can contain any type of variable, strings, booleans, numbers, arrays and objects. It's easy to extend, manipulate & traverse, as complexity comes along.
var data = {};
// I prefer the string literal, but you could also:
var blah = new Object();
Now we have an object. Let's add some attributes to it.
data["articles"] = [];
data.count = 0;
You can choose whether to use the dot annotation or array access. I do both depending on whether I'm adding keys with variables or have keys with spaces.
data["ev_" + i] = true;
data["a space in here"] = 1000;
If you need to loop or check for a key in an objects, you could use the in statement.
if("localStorage" in window){
if("articles" in window.localStorage){
data.articles = eval(window.localStorage.articles);
for(var key in data.articles){
var article = data.articles[key];
}
}
}
Be aware of that you can never order an object, so if you need ordered lists you have to use an array for that. Well that's it for this weeks code tip. Tune in next week for more.