如何对具有重用键的对象使用嵌套解构?

时间:2019-01-06 21:14:01

标签: javascript syntax-error

我从网络套接字中收到一条消息:

var message = {
  spell: {
    symbol: 'my-spell'
  },
  target: {
    symbol: 'my-target'
  }
};

我正在尝试学习解构,所以我编写了以下代码:

let {
  spell: {
    spell_symbol: symbol
  },
  target: {
    target_symbol: symbol = null
  }
} = message;
console.log('spell symbol: ' + spell_symbol);
console.log('target symbol: ' + target_symbol);

这给了我一个错误:

SyntaxError: Identifier 'symbol' has already been declared

我是否将语法写错了,还是不能在嵌套对象中重用symbol之类的键?我将如何从target.symbol中提取message

1 个答案:

答案 0 :(得分:2)

您混合了属性名称和目标表达式的顺序,应该是

const {
  spell: {
    symbol: spell_symbol
  },
  target: {
    symbol: target_symbol = null
  }
} = message;
console.log('spell symbol: ' + spell_symbol);
console.log('target symbol: ' + target_symbol);