将值从数组保存到javascript中的变量。

时间:2020-12-07 21:17:48

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

因此,我得到了JSON数据,我将它保存到一个变量中,它是一个数组。

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?

所以,我的问题是:我是在用正确的方式来做这件事吗?有些事情是不正确的,或者这段代码是完全错误的吗?

3 个解决方案

#1


0  

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:

这只适用于满足变量命名规则的属性,这意味着像{“streetand city”:“……”不能使用点符号来访问}。你必须像这样访问这些属性:

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

#2


0  

The returned object is an object, it's not array. So there is no need to use .filter here. Just do

返回的对象是一个对象,它不是数组。所以这里没有必要使用。filter。只做

console.log(my_data.city);

#3


0  

thanks everyone! now I realized I went too deep

谢谢大家!现在我意识到我走得太深了。

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

var my_city = my_data.city;

works fine

工作正常

#1


0  

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:

这只适用于满足变量命名规则的属性,这意味着像{“streetand city”:“……”不能使用点符号来访问}。你必须像这样访问这些属性:

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

#2


0  

The returned object is an object, it's not array. So there is no need to use .filter here. Just do

返回的对象是一个对象,它不是数组。所以这里没有必要使用。filter。只做

console.log(my_data.city);

#3


0  

thanks everyone! now I realized I went too deep

谢谢大家!现在我意识到我走得太深了。

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

var my_city = my_data.city;

works fine

工作正常