Poke
Poke

Reputation: 45

retrieve all data from firebase using javascript

This is my data structure:

{
 "Country" : {
    "USA" : {
       "Latitude" : 37.0902,
       "Longitude" : 95.7129
     },
     "Japan" : {
       "Latitude" : 36.2048,
       "Longitude" : 138.2529
     }
}

Hello. How do I retrieve the country key which is "USA" and "Japan" and also the Latitude and Longitude for both of them using just javascript. I would like to retrieve all as the number of country is increase. Thanks

Upvotes: 0

Views: 114

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can do this with Object.keys() and forEach() loop

var obj = {
  "Country": {
    "USA": {
      "Latitude": 37.0902,
      "Longitude": 95.7129
    },
    "Japan": {
      "Latitude": 36.2048,
      "Longitude": 138.2529
    }
  }
}

Object.keys(obj.Country).forEach(function(e) {
  console.log(e);
  Object.keys(obj.Country[e]).forEach(function(a) {
    console.log(obj.Country[e][a]);
  });
});

You can also create string in each iteration of loop and console.log() that string. This way you can return coutry and Latitude, Longitude in one line.

var obj = {
  "Country": {
    "USA": {
      "Latitude": 37.0902,
      "Longitude": 95.7129
    },
    "Japan": {
      "Latitude": 36.2048,
      "Longitude": 138.2529
    }
  }
}

Object.keys(obj.Country).forEach(function(e) {
  var str = e + ' ';
  Object.keys(obj.Country[e]).forEach(function(a) {
    str += obj.Country[e][a] + ' ';
  });
  console.log(str)
});

Upvotes: 2

Ben Aston
Ben Aston

Reputation: 55729

// `inbound` is the JSON
var data = JSON.parse(inbound);
var usa = data.Country['USA'];
var usaLat = usa.Latitude;
// etc

Upvotes: 0

Related Questions