Poke Poke - 2 months ago 12
Javascript Question

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

Answer

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)
});

Comments