Reputation: 629
I am using some AngularJS to retrieve values in my Firebase Database under a specified parent tree. I would like to get also the value of this parent.
My database structure:
So far, my code gets the Name and PhotoUrl of each tripID under a specified UserID. But I would like to get the TripID value as well as the Name and PhotoUrl. The problem is that the TripID value is not in the child tree. How can I retrieve it ?
My JS looks like this:
var app = angular.module('test', []);
app.controller('MainCtrl', function($scope) {
var database = firebase.database();
database.ref(`trips/${userid}/trips`).once('value')
.then(photosSnap => {
var photosObj = photosSnap.val();
var tripName = Object.keys(photosObj).map(key => photosObj[key].name);
var tripPhotoUrl = Object.keys(photosObj).map(key => photosObj[key].photourl);
$scope.repeatData = tripName.map(function (value, index) {
return {
data: value,
value: tripPhotoUrl[index]
}
});
Upvotes: 0
Views: 1387
Reputation: 598728
Not sure if I understand correctly, but if you want a list of the trip keys:
var tripKeys = Object.keys(photosObj);
But extracting the separate values into arrays and then recomposing feels overly complex to me. You can just loop over the trips once to get all the data you need:
var trips = photosSnap.val();
$scope.repeatData = Object.keys(trips).map((key) => {
tripKey: key,
tripName: trips[key].name,
tripPhotoUrl: trips[key].photourl
});
Or without needing Object.keys()
:
var trips = [];
photosSnap.forEach((trip) => {
trips.push({
tripKey: trip.key,
tripName: trip.val().name,
tripPhotoUrl: trip.val().photourl
});
});
$scope.repeatData = trips;
The last bit unfortunately requires a temporary variable, since Firebase's DataSnapshot
class doesn't have a map()
function.
Upvotes: 1