I read through Javascript The Good Parts, and learned that using for (i in blah) {} is bad notation, but the problem is, I'm using Node.js and the database I'm using MongoDB returns all its queries as objects which is fine. Right now I have an ajax query that pulls all information from a table, and I want to do things with each value.
But what the database is returning is an array (with a random size depending on whats in the database) that contains objects, for clarity sake I'll give you an example:
[
{
'a': 'value of a',
'b': 'value of b',
'c': 'value of c'
},
{
'a': 'value of a',
'b': 'value of b',
'c': 'value of c'
}
]
How can I iterate through each thing so that I can assign variables from each one this is what I have worked up:
for (var i = 0; i < data.success.length; i += 1) {
for(x in data.success[i]) {
console.log(x);
}
}
I'm just worried that the bad notation will bite me in the end, I read that the (blah in blah) notation doesn't always return results in order. Which this HAS to be in order. Hope I made myself clear, thanks.
I need to get the values, not the name of the variable in the object.
Object.keys(data.success[i]) will give you all of the keys present in an object, which you can then .sort to guarantee sort order.
data.success.forEach(function(item, n) {
console.log('item ' + n);
Object.keys(item).sort().forEach(function(key) {
console.log(key + ':' + item[key]);
});
});