javascript - 解构大(嵌套)对象的最佳方法是什么?
问题描述
我的目标是解构大(嵌套)对象并将其属性分配给变量,目前我有:
const { name, country, sunrise, sunset, timezone } =
this.state.weather?.city || {};
const { temp, feels_like } =
this.state.weather.list?.[0].main || {};
是否有任何其他选项可以缩短/更好地适应此代码?
解决方案
编辑:
关键概念:
解构对象:
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)
原答案:
以下是如何进行嵌套对象和数组解构:
// 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);
推荐阅读
- python - 为数据框中的每一行绘制图表并保存为 jpg 格式?
- python - 删除具有一定百分比 0 的 pandas 的列和行
- php - 由于两个表之间的外键约束而无法登录
- node.js - node_module 和 aws lambda 函数
- cordova - Ionic-4 轮选择器/选择器按钮 css 自定义
- angular - 如何在没有角度材料日期选择器的情况下使用
- apache-kafka - kafka在消费消息时崩溃
- ios - 如何从数组中随机设置 textFiledPlaceholder 文本
- android - IllegalArgumentException:尝试删除从未添加的 OnFrameMetricsAvailableListener
- node.js - Webpack 1 到 4 的升级变得如此复杂