Chris Simmons
Chris Simmons

Reputation: 259

How to join Json response element

I am making a call to the OpenWeatherApi am facing a dilemma. I am pulling the response, but only need specific data elements. I am successfully pulling certain elements, but am having trouble pulling the CITY element.

This is the response from the API call:

{
"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

}

This is my mapping for the specific elements I need:

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)

Finally, this is the response from my mapping:

{
"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

}

As you can see, CITY is split up into separate elements. If I only pull CITY, it pulls the accurate City just fine, as "Cincinnati" not "name": "Cincinnati".

How can I join the elements for form the city, or recreate the "name": "City" element altogether?

Upvotes: 0

Views: 31

Answers (1)

abhirathore2006
abhirathore2006

Reputation: 3745

you are getting wrong result because city is an array and its getting spread. change your code to below code

Object.assign({}, main, weather, sys, {city})
  or 
Object.assign({}, main, weather, sys, {name:city})

Solution is to convert array value to object property.

Upvotes: 2

Related Questions