Max Harbarth Max Harbarth - 2 months ago 9
Javascript Question

Save value from array to variable in javascript

So, I'm getting JSON data, which I save to a variable and which is an array.

var my_data
$.getJSON('http://ipinfo.io/geo', function(data){
my_data = data;
console.log(my_data);
});


in console I have this:

Object {
city: "Krasnoyarsk",
country: "RU",
ip: "212.119.233.96",
loc: "56.0184,92.8672",
postal: "660000",
region: "Krasnoyarskiy Kray"
}


but the only thing I need from this array is the name of the city. I tried the following:

var my_city = my_data.filter(function (filt) {
return filt.city;});


but this doesn't seem to work.

So, my question is: am I trying to do this in a right way and something is just not right OR is this code completely wrong?

Answer

You can access properties of an Object simply by using dot-notation like:

var myCity = my_data.city;

This only works for properties which fulfill the naming rules for variables, which means something like { "street-and-city": '...' } can't be accessed by using dot-notation. You have to access these properties like this:

var myStreetAndCity = my_data["street-and-city"];