javascript - 嵌套对象解构 - 如何处理可能丢失的嵌套对象
问题描述
我努力想出这个。在下面的小提琴中,我如何解释 itemChild 可能不存在的情况?当我删除它时,我收到以下错误(索引):49 Uncaught TypeError: Cannot read property 'cat' of undefined
const item = {
name: "firstItem",
color: "red",
shape: "square",
size: "big",
itemChild: {
cat: "category1",
age: "10"
}
}
let {
name,
color,
shape,
size,
itemChild = {},
itemChild: {
cat = "",
age = ""
}
} = item;
if (itemChild) {
console.log("Child", cat, age);
} else {
console.log("Parent", name, color);
}
解决方案
您可以使用默认值
const item = {
name: "firstItem",color: "red",shape: "square",size: "big",
itemChild: {
cat: "category1",
age: "10"
}
}
const func = (obj) => {
let {
name, color, shape, size,
itemChild: { cat = "", age = "" } = { cat: 'meow', dog: 'bark'}
} = obj;
console.log(name,color,shape,size, cat, age)
}
func(item)
const { itemChild, ...noItemChild } = item
func(noItemChild)
推荐阅读
- python - 从数据框行中获取前 3 个值的索引(使用快速实现)
- java - 如何在 YouTube Data API 的数据中正确打印“外来”/特殊字符?
- python - 从数组中设置变量
- php - php按数字插入多个数据
- amazon-web-services - 创建 CloudFormation 模板以创建多个 Glue 连接
- apim - 用于多租户 Azure Web 应用程序的 APIM validate-jwt:IDX10205
- reactjs - 打字稿,使用字符串查找枚举
- python - 从与 VegaLite/Altair 图的交互中向外发射信号/事件的解决方法?
- nifti - 使用 nibabel 的图像方向
- c# - 当我使用 DropDownListFor 时,我可以显示所选项目但 Id 不正确