Let's say I have the following Javascript JSON object (I used strings as the values but they could be anything: objects, functions, etc...):
var f = {
foo: 'bar1',
bar: 'bat1',
bat: 'baz1'
};
The call
f.foo would return the string 'bar1' (sans quotes).
But, what if you have a JSON object and you want to iterate over all the values, but you don't know all the keys? The following will generate an alert box for each key/value pair but the alert is simply used to show the results and any type of processing could be done instead:
for (item in f) {
alert(item + ', ' + f[item]);
}
NB: Two major caveats:
- Because of namespace pollution by, shall we say, less than kosher JavaScript APIs, you can get whamboozled here through JavaScript's allowance of the
prototype operator in that items can be magically added to your hash without your knowledge.
While this is a bug (not a flaw as some websites state) in JavaScript, the onus is on the developer to ensure they don't pollute the namespace with their code. jQuery is very good about this by ensuring that everything is encapsulated so no pollution occurs.
- As it is a hash, we are NOT guaranteed the order over which items will be iterated. This can easily be mitigated by using an array to store the keys separately and then iterate over the array to get the correct order. It should be noted that in this case, we can retrieve the length of the hash via the lenth field on the array and thus, don't need the for-in loop.
for (item in f) {
if (f.hasOwnProperty(item)) {
alert(item + ', ' + f[item]);
}
}
This ensures that we only read items that we placed in the hash - we, unfortunately, still iterate over items that are not ours.
0 comments:
Post a Comment