在析构时处理嵌套对象上缺少的属性

Lir*_*anC 3 javascript ecmascript-6

我需要解构嵌套对象。当某些嵌套属性丢失时,在分配确实存在的属性时避免异常的最佳方法是什么?

const data = {
  title: 'hello',
  // nest: {
  //   road: 5
  // }
};

const { title, nest: { road = '' } } = data;

console.log(road);
/** i want it to return '' or undefined. 
 *  actually it returns: Cannot match against 'undefined' or 'null'
 * 
*/
console.log(title)
/** i want it to return 'hello'
 * actually: never got there as there was an exception.
 */
Run Code Online (Sandbox Code Playgroud)

Kou*_*jee 5

即使它具有进一步嵌套的对象销毁,您也可以在父对象级别分配给空对象(或带值):

const { title, nest: { road = '<default road>' } = {} } = data;
Run Code Online (Sandbox Code Playgroud)

const data = {
  title: 'hello',
   //nest: {
   //  road: 5
   //}
};

const { title, nest: { road = '<default road>' } = {} } = data;

console.log(title);
console.log(road);
Run Code Online (Sandbox Code Playgroud)

而且,你做错了,如果你正在破坏使用

{title: englishTitle} = {title: 1234}
Run Code Online (Sandbox Code Playgroud)

然后,您应该使用englishTitle来获取 value 1234,而不是title,或者使用

{title} = {title: 1234}
Run Code Online (Sandbox Code Playgroud)

并使用title得到1234