Max Harbarth Max Harbarth - 1 year ago 102
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('', function(data){
my_data = data;

in console I have this:

Object {
city: "Krasnoyarsk",
country: "RU",
ip: "",
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) {

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 Source

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

var myCity =;

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"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download