Iterating through nested firebase objects - Javascript
How to iterate through nested firebase objects.
Publications-
|
|-Folder1------
| |-hdgjg76675e6r-
| | |-Name
| | |-Author
| |
| |+-hdgjdsf3275e6k
| |+-hd345454575e6f
|+-Folder2
In publications I have folders and in folders I have objects (containing properties like. Name, Author)
I've been going through the folders so far.
snapshot.forEach(function (snapshot) {
var key = snapshot.key();
var obj = snapshot.val();
console.log(key);
//output => Folder1 , Folder2 etc
});
When I type obj
console.log(obj);
Displayed
How do I iterate through the obj variable as it contains hdgjg76675e6r
, hdgjdsf3275e6k
etc. and further?
source to share
You obj
are a regular javascript object, you can just use a simple loop:
for(var key in obj) {
console.log(obj[key]);
}
or you can use again forEach
in your snapshot:
folderSnapshot.forEach(function (objSnapshot) {
objSnapshot.forEach(function (snapshot) {
var val = snapshot.val();
console.log(val); // Should print your object
});
});
source to share
Will the tree go deeper? If not, the best solution here would be to just do a double loop.
snapshot.forEach(function (snapshot) {
var key = snapshot.key();
var obj = snapshot.val();
console.log(key);
//output => Folder1 , Folder2 etc
obj.forEach(function (book) {
var title = book.title;
var author = book.author;
});
});
I don't need to overestimate things in my opinion.
source to share