1

My Firebase data base contains JSON objects, each with the same parameters as seen below. Firebase data

I want to get an array that has each objects country. So if I have 4,000 objects I want to get an array of 4,000 strings all containing a country.

Right now I can get the console to log all the 4,000 objects into an array using the code below.

componentWillMount() { this.fetchData(); } fetchData = async () => { var data1 = []; var fireBaseResponse = firebase.database().ref(); fireBaseResponse.once('value').then(snapshot => { snapshot.forEach(item => { var temp = item.val(); data1.push(temp); return false; }); console.log(data1); }); } 

But when I try doing

 var fireBaseResponse = firebase.database().ref().child('country'); 

I get an array of nothing.

Any help would be great.

5
  • I believe you have to use snapshot.val() to access the returned object Commented Jul 10, 2018 at 17:30
  • I do for each item and I do get an array of 4,000 objects. The thing is the array has all the item info and not just country. Commented Jul 10, 2018 at 17:33
  • Then you should extract item.val().country into a new object before pushing it into data1. I hope this helps! Commented Jul 10, 2018 at 17:35
  • Your right. I cannot believe I did not see that. Thanks so much Commented Jul 10, 2018 at 17:36
  • No problem. Glad I could help Commented Jul 10, 2018 at 17:41

1 Answer 1

1

As mentioned in the comments, you can create a new temp object containing just country before pushing it into your array.

snapshot.forEach(item => { var temp = { country: item.val().country }; data1.push(temp); return false; }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.