Search code examples
javascriptreactjsdestructuring

A cleaner way of Object Destructuring, i.e. nesting?


I'm using Object Destructuring. And my app works completely fine. However it looks a bit untidy. I tried nesting however I got errors.

The destructuring looks like this so far:

  const { response = [] } = res;
  const { weather = [], main = [] } = response;
  const { humidity, temp_min, temp_max, feels_like, temp } = main;
{
  "response": {
    "coord": {
      "lon": 69.42,
      "lat": 34.5
    },
    "weather": [
      {
        "id": 500,
        "main": "Rain",
        "description": "light rain",
        "icon": "10d"
      }
    ],
    "base": "stations",
    "main": {
      "temp": 12.15,
      "feels_like": 7.43,
      "temp_min": 12.15,
      "temp_max": 12.15,
      "pressure": 1017,
      "humidity": 27,
      "sea_level": 1017,
      "grnd_level": 812
    },
    "wind": {
      "speed": 2.83,
      "deg": 77
    },
    "rain": {
      "3h": 0.72
    },
    "clouds": {
      "all": 12
    },
    "dt": 1585210208,
    "sys": {
      "country": "AF",
      "sunrise": 1585185447,
      "sunset": 1585229894
    },
    "timezone": 16200,
    "id": 1138957,
    "name": "Kabul",
    "cod": 200
  },
  "error": null
}

Is there a way to do this on one or even two lines?


Solution

  • You can use:

    const {
       response: {
          weather = [],
          main: {
             humidity,
             temp_min,
             temp_max,
             feels_like,
             temp
          } = {}
       } = {}
    } = res;
    

    Or, in one-line like:

    const { response: { weather = [], main: { humidity, temp_min, temp_max, feels_like, temp } = {} } = {} } = res;
    

    DEMO:

    const res = { response: { coord: { lon: 69.42, lat: 34.5 }, weather: [{ id: 500, main: "Rain", description: "light rain", icon: "10d" }], base: "stations", main: { temp: 12.15, feels_like: 7.43, temp_min: 12.15, temp_max: 12.15, pressure: 1017, humidity: 27, sea_level: 1017, grnd_level: 812 }, wind: { speed: 2.83, deg: 77 }, rain: { "3h": 0.72 }, clouds: { all: 12 }, dt: 1585210208, sys: { country: "AF", sunrise: 1585185447, sunset: 1585229894 }, timezone: 16200, id: 1138957, name: "Kabul", cod: 200 }, error: null };
    const { response: { weather = [], main: { humidity, temp_min, temp_max, feels_like, temp } = {} } = {} } = res;
    
    console.log({ humidity, temp_min, temp_max, feels_like, temp })

    Please notice that in your code first part:

    const { response = [] } = res;  
    

    you have set response to a default empty array, but response in res is actually an object, so you should default it to {} instead. Need to do the same for main = [] in your code.