分解大型(嵌套)对象的最佳方法是什么? [英] What is the best way to destructure big (nested) object?

查看:88
本文介绍了分解大型(嵌套)对象的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?.city || {};
    
const { temp, feels_like } =
   this.state.weather.list?.[0].main || {};

还有其他选择可以缩短/更好地适合此代码吗?

Is there any other option which can shorten/fit better this code?

推荐答案

关键概念:

  1. 解构对象:

  1. Destructuring objects:

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

解构数组:

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

解构对象数组:

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

这篇关于分解大型(嵌套)对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆