我正在给OpenWeatherApi打电话,面临一个难题。我正在拉响应,但只需要特定的数据元素。我已经成功提取了某些元素,但是在提取 CITY 元素时遇到了麻烦。
这是API调用的响应:
{
"coord": {
"lon": -122.4,
"lat": 45.64
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 287.5,
"pressure": 1022,
"humidity": 82,
"temp_min": 284.25,
"temp_max": 289.25
},
"visibility": 16093,
"wind": {
"speed": 0.96,
"deg": 10.5029
},
"clouds": {
"all": 1
},
"dt": 1537854780,
"sys": {
"type": 1,
"id": 2321,
"message": 0.0172,
"country": "US",
"sunrise": 1537884050,
"sunset": 1537927234
},
"id": 420040945,
"name": "Vancouver",
"cod": 200
}
这是我对所需特定元素的映射:
const main = response.data["main"]
const sys = response.data["sys"]
const city = response.data.name;
const weather = response.data["weather"][0]
const data = Object.assign(main, weather, sys, city)
res.send(data)
console.log(data)
最后,这是我的映射的响应:
{
"0": "C",
"1": "i",
"2": "n",
"3": "c",
"4": "i",
"5": "n",
"6": "n",
"7": "a",
"8": "t",
"9": "i",
"temp": 293.74,
"pressure": 1018,
"humidity": 90,
"temp_min": 293.15,
"temp_max": 294.25,
"id": 2179,
"main": "Rain",
"description": "light rain",
"icon": "10n",
"type": 1,
"message": 0.0044,
"country": "US",
"sunrise": 1537874932,
"sunset": 1537918192
}
如您所见,城市分为多个单独的元素。如果我只拉 CITY ,它会精确拉出准确的城市,因为 “辛辛那提” 不 “ name”:“辛辛那提”。
我如何加入组成城市的元素,或者重新创建“名称”:“城市”元素?
答案 0 :(得分:2)
您得到的是错误的结果,因为city是一个数组并且它的传播范围越来越大。将您的代码更改为以下代码
Object.assign({}, main, weather, sys, {city})
or
Object.assign({}, main, weather, sys, {name:city})
解决方案是将数组值转换为对象属性。