Skip to content Skip to sidebar Skip to footer

What Is The Best Way To Destructure Big (nested) Object?

My goal is to destructure big (nested) object and assign it properties to variables, currently I have: const { name, country, sunrise, sunset, timezone } = this.state.weather?.c

Solution 1:

Edit:

Key concepts:

  1. Destructuring objects:

    const data = { id: 1, name: "SO" }
    const { id, name, city = "N/A" } = data
    console.log(id, name, city);
  2. Destructuring arrays:

    const data = [ 1, 2 ]
    const [first, second, third = "N/A"] = data
    console.log(first, second, third)
  3. Destructuring array of objects:

    const data = [ {id: 1, name: "SO"} ]
    const [ { id, name, city = "N/A" }, second = {} ] = data
    console.log(id, name, city, second)

Original answer:

Here is how to do Nested object and array destructuring:

// Input data
const that = {
  state: {
    weather: {
      city: {
        name: "new york",
        country: "usa",
        sunrise: "6 AM",
        sunset: "7 PM",
        timezone: "-4"
      },
      list: [{
        main: {
          temp: 10,
          feels_like: 14
        }
      }]
    }
  }
};

// Nested Destructuring
const {
  city: {
    name,
    country,
    sunrise,
    sunset,
    timezone
  },
  list: [{
    main: {
      temp,
      feels_like
    }
  }, second]
} = that.state.weather;

// Results
console.log(name, country, sunrise, sunset, timezone);
console.log(temp, feels_like);

With default values to avoid error - "can not read property of undefined":

// Input data
const that = {
  state: {}
};

// Nested Destructuring
const {
  city: {
    name,
    country,
    sunrise,
    sunset,
    timezone
  } = {},
  list: [{
    main: {
      temp,
      feels_like
    } = {}
  } = {}, second] = []
} = that.state.weather ?? {};

// Results
console.log(name, country, sunrise, sunset, timezone);
console.log(temp, feels_like);

Post a Comment for "What Is The Best Way To Destructure Big (nested) Object?"