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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With