Reputation: 369
I am trying to iterate over elements of, what I think is, a Map
object and getting the following error:
TypeError: cr.forEach is not a function
at exports.onNewOrder.functions.database.ref.onCreate.event (/user_code/index.js:122:12)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:728:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Here is the code I am running from within Google Cloud Function:
function logMapElements(value, key, mapObj) {
console.log(`m[${key}] = ${value}`);
}
exports.onNewOrder = functions.database.ref('/orders/{orderId}').onCreate(event => {
const data = event.val();
const cr = data.crs;
console.log(cr);
cr.forEach(logMapElements);
}
This is what printed in the log by console.log(c)
:
{ cr_36446aba912c45d0956e57cbf0a4e165: 1, cr_d46f4c12119e45478a0aa2867df55e09: 1 }
What am I doing wrong here?
Upvotes: 0
Views: 585
Reputation: 598901
While the answers from Sidhanshu_, user9977547, and Fabien Greard all may work, I consider using Firebase's built-in DataSnapshot.forEach
method to be more idiomatic:
exports.onNewOrder = functions.database.ref('/orders/{orderId}').onCreate(event => {
event.child("crs").forEach(child => {
console.log(child.val());
});
}
While the result between Array.forEach()
and DataSnapshot.forEach()
will be the same here, it has a subtle difference in some other cases. When you query data from the Firebase Database, DataSnapshot.forEach()
will iterate the children in the requested order, while you'll typically have lost that order by the time you get to Array.forEach()
. To avoid subtle bugs, I recommend using DataSnapshot.forEach()
for any data from the Firebase Database.
Upvotes: 2
Reputation: 2110
You have to use it like :
Object.keys(object).map(function(objectKey, index) {
var value = object[objectKey];
console.log(value);
});
Upvotes: 1
Reputation: 51
Because cr is not an array you
can’t use methods of an array with it. Try to use use a for (bar propertyName in object)
loop here.
for(var id in cr){
var value = cr[id]
...
}
Upvotes: 1
Reputation: 1894
forEach()
only work on array, cr
is an object
.
You could use map()
instead. Or convert your obect into an array with Object.values()
(also see Object.keys()
, Object.entries()
Upvotes: 1