Javascript 如何仅在存在密钥时分解对象

Javascript 如何仅在存在密钥时分解对象,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,如何仅当对象中存在键时才分解对象,或者应该说使用条件分解对象 const arts = { a: 23, b: 3, c: 5} const {a, d} = arts console.log(d) // result produces an error on execution 我想要一个代码,其中d如果不是对象中可用的键,就不会被解构 const arts = { a: 23, b: 3, c: 5} if(arts.hasOwnProperty('a')) { const {a}

如何仅当对象中存在键时才分解对象,或者应该说使用条件分解对象

const arts = { a: 23, b: 3, c: 5}
const {a, d} = arts
console.log(d) 
// result produces an error on execution
我想要一个代码,其中d如果不是对象中可用的键,就不会被解构

const arts = { a: 23, b: 3, c: 5}

if(arts.hasOwnProperty('a')) {
  const {a} = arts
  console.log(a)
  // do something with a
}
else {
  console.log('a was not found in arts');
}

if(arts.hasOwnProperty('d')) {
  const {d} = arts
  console.log(d)
  // do something with d
}
else {
  console.log('d was not found in arts');
}
使用上文定义的arts将输出:

23
d was not found in arts

hasOwnProperty方法返回一个布尔值,指示对象是否将指定的属性作为自己的属性而不是继承它

您可以指定一个默认值。有条件地创建一个变量似乎很奇怪,因为可能存在使用该变量的代码。在上面的示例中,如果d不存在,那么console.logd.d应该发生什么将自动取消定义。这种行为似乎是最合理的。你试过const{a,d}=arts||{}吗?除了未定义之外,你还能期待什么呢?上面的代码不会引发错误。如果在其他地方出现错误,则必须更新逻辑以处理该值。const{a,d}=arts创建两个变量a和d。如果你不想要d,那么就不要包括它。常数{a}=艺术。如果我们不真正了解你想做什么,就很难提出建议。