0

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

4
  • Can you show desired output? Commented Jul 13, 2016 at 15:47
  • could console.log the country name and the coordinate Commented Jul 13, 2016 at 16:05
  • So you just want to log for example USA and 37.0902 95.7129 etc? Commented Jul 13, 2016 at 16:06
  • yes. i want the log to appear like that Commented Jul 13, 2016 at 16:07

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

what if i want to retrieve the Latitude and Longitude separately? How to I do that?
i mean is that anyway to store latitude and longitude in separate string variable?
How to I retrieve latitude and longitude for the two countries where two different variable is used to store latitude and longitude. For example , var latitude = latitude of the country and var longitude = longitude of the country. Thanks for the help !
Maybe you should post that as new question.
0
// `inbound` is the JSON
var data = JSON.parse(inbound);
var usa = data.Country['USA'];
var usaLat = usa.Latitude;
// etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.