【问题标题】:How can I use nested destructuring with objects with reused keys?如何对具有重用键的对象使用嵌套解构?
【发布时间】:2019-01-06 21:14:00
【问题描述】:

我的 websocket 有一条消息:

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 之类的键?如何从message 中提取target.symbol

【问题讨论】:

    标签: javascript syntax-error


    【解决方案1】:

    你把属性名和目标表达式的顺序搞混了,应该是

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

    【讨论】:

    • @DavidBray 请参阅herethere 了解说明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2020-04-09
    • 2021-07-16
    • 2022-11-20
    • 2023-03-18
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多