Neekoy Neekoy - 5 months ago 33
Node.js Question

Node Async forEach - How to iterate by keys instead of values

I currently have the following example object:

"fruit" : [ { "bananas" : 2, "tomatoes" : 3 } ];


Let's say I'm iterating through it with the following code:

console.log(fruit);

async.forEach(fruit, function(item, callback) {
console.log(item);
callback();
}, function(err) {
console.log("Iterating done.");
}
);


My output is the following:

{ 'bananas': 2, 'tomatoes': 3 }
2
3
Iterating done.


The separate console.log gives me the information I need, however async.forEach gives me only the values. Is it possible to have async.forEach output the keys of the object instead?

Answer

Iterate over Object.keys(fruit) instead of fruit:

async.forEach(
    Object.keys(fruit),
    function(item, callback) {
        console.log(item);
        callback();
    },
    function(err) {
        console.log("Iterating done.");
    }
);