【问题标题】:Nested object destructuring - how to handle possible missing nested object [duplicate]嵌套对象解构-如何处理可能丢失的嵌套对象[重复]
【发布时间】:2023-03-18 20:38:01
【问题描述】:

我正在努力解决这个问题。在下面的小提琴中,我如何解释 itemChild 可能不存在的情况? 当我删除它时,我收到以下错误 (index):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/

【问题讨论】:

  • 您需要将嵌套的目标赋值和默认值加入到同一个属性元素中:itemChild: { cat = "", age = "" } = {}。您的两个 itemChild 目标是分开的。
  • 嘿,谢谢,为什么默认赋值不在元素本身上?...所以当 itemChild 未定义时,它会变成 {} ?
  • 这只是语法:propertyName: assignmentTarget = defaultValue。它正是这样做的。

标签: javascript


【解决方案1】:

你可以使用默认值

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)

【讨论】:

  • 我如何检查 itemChild 是否存在?
  • 只有当 itemchild 不存在( undefined )时才会分配默认值,因此您可以使用这个事实来检查 itemchild 是否存在
  • @blu10 您必须将其拆分为单独的语句。目前itemChild 有一个默认值,因此始终存在。相反,您想先提取它而不使用默认值。 let {name, color, shape, size, itemChild} = obj 然后检查itemChild 的存在。如果您需要提取itemChild 的属性,您可以稍后再做let {cat = "", age = ""} = itemChild。
  • @3limin4t0r 这可能是一个更简洁的方法,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2022-08-23
  • 2013-09-29
  • 2018-04-26
  • 2021-11-16
  • 1970-01-01
相关资源
最近更新 更多