Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 — How to destructure from an object with a string key?

I have an object

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

being passed into a function

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
}

but of course hello_zh-CN is not a valid key name.

I am unable to write

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

as that gives an error.

How can I destructure an object's properties when one of the keys is a string?

like image 821
Dave Sag Avatar asked Jun 03 '17 12:06

Dave Sag


People also ask

Can you Destructure a string?

JavaScript String Splitting and Array DestructuringAs the split method returns an array, we can use the array destructuring syntax to get the element from the array. That's all for now.

Can you Destructure array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

Can we Destructure function in JavaScript?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays.


1 Answers

Destructure it by providing a valid key name like

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

Working snippet

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);
like image 156
Shubham Khatri Avatar answered Oct 12 '22 05:10

Shubham Khatri