首页 > 解决方案 > 解构大(嵌套)对象的最佳方法是什么?

问题描述

我的目标是解构大(嵌套)对象并将其属性分配给变量,目前我有:

const { name, country, sunrise, sunset, timezone } =
   this.state.weather?.city || {};
    
const { temp, feels_like } =
   this.state.weather.list?.[0].main || {};

是否有任何其他选项可以缩短/更好地适应此代码?

标签: javascriptarraysecmascript-6javascript-objectsdestructuring

解决方案


编辑:

关键概念:

  1. 解构对象:

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

  2. 解构数组:

    const data = [ 1, 2 ]
    const [first, second, third = "N/A"] = data
    console.log(first, second, third)

  3. 解构对象数组:

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


原答案:

以下是如何进行嵌套对象和数组解构:

// 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);

使用默认值以避免错误 - “无法读取未定义的属性”:

// 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);


推荐阅读