首页 > 解决方案 > 嵌套对象解构 - 如何处理可能丢失的嵌套对象

问题描述

我努力想出这个。在下面的小提琴中,我如何解释 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);
}

https://jsfiddle.net/1w68j2cv/2/

标签: javascript

解决方案


您可以使用默认值

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)


推荐阅读