ES6 — 如何使用字符串键解构对象?

问题描述 投票:0回答:2

我有一个对象

{
  hello_en: 'hello world',
  'hello_zh-CN': '世界您好',
  something: 'nice day',
  something_else: 'isn\'t it'
}

被传递到函数中

function(data) {
  const { hello_en, hello_zh-CN, ...rest } = data
  // do some stuff with hello_en and hello_zh-CN
  // so some other stuff with rest
}

但是当然

hello_zh-CN
不是有效的密钥名称。

我无法写作

const { hello_en, 'hello_zh-CN', ...rest } = data

因为这会产生错误。

当其中一个键是字符串时,如何解构对象的属性?

javascript ecmascript-6 destructuring
2个回答
60
投票

通过提供有效的键名称来解构它,例如

  const { hello_en, 'hello_zh-CN': hello_zHCN, ...rest } = data

工作片段

var data = {
  hello_en: 'hello world',
  'hello_zh-CN': '世界您好',
  something: 'nice day',
  something_else: 'isn\'t it'
}

const { hello_en, 'hello_zh-CN': hello_zHCN, ...rest } = data

console.log(hello_zHCN);


0
投票
let data = {
    hello_en: 'hello world',
    'hello_zh-CN': '世界您好',
    something: 'nice day',
    something_else: 'isn\'t it'
}
const { 'hello_zh-CN': xd } = data;
© www.soinside.com 2019 - 2024. All rights reserved.