在destructring处理嵌套对象上的缺失属性

时间:2017-08-30 13:47:29

标签: 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.
 */

1 个答案:

答案 0 :(得分:3)

您可以在父对象级别中将空对象分配给空对象,即使它具有进一步的嵌套对象销毁:

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

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

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

console.log(title);
console.log(road);

而且,如果你正在破坏使用,你做错了 {title: englishTitle} = {title: 1234}然后,您应该使用englishTitle获取值1234,而不是标题,或使用{title} = {title: 1234}并使用title得到1234