Warm tip: This article is reproduced from serverfault.com, please click

Alternative to foreach loop for Datasnapshot so I can exit loop when condition is met?

发布于 2020-11-28 07:10:13

I am currently running a forEach loop like bellow:

snapshot.forEach((theChild) => 
   let newPostID1 = String(snapshoot.key);
   let newUID = String(child.key);
   //Spill coffee here.
})

ForEach loops do not allow you to exit after a condition is met.

What is an alternative method of looping through my snapshot which allows me to return (exit) after a condition is met?

Questioner
NCT 127
Viewed
0
Doug Stevenson 2020-11-28 15:45:33

You can use val() to get a JavaScript object with the entire set of data at the snapshot. Then you can iterate its keys using standard JavaScript object property iteration with for..in and break whenever you want.

const val = snapshot.val()
for (const key in val) {
    console.log(`child key: ${key}`)
    console.log(`child value: ${val[key]}`)
    // break whenever you want
}