Is there a way to destructure
an object having a hyphen in the property names. I get a SyntexError
while doing so (which is reasonable because JS doesn't allow variable name with a hyphen
).
let human= {
"first-name":"John",
"last-name":"Doe",
age:150
}
let {age}= human;
// let {"first-name"}= human;//error
// let {first-name}= human;//error
console.log(age)
Is there a way to destructure
an object having a hyphen in the property names. I get a SyntexError
while doing so (which is reasonable because JS doesn't allow variable name with a hyphen
).
let human= {
"first-name":"John",
"last-name":"Doe",
age:150
}
let {age}= human;
// let {"first-name"}= human;//error
// let {first-name}= human;//error
console.log(age)
Share
Improve this question
asked Jul 16, 2018 at 8:06
Sandeep GuptaSandeep Gupta
7,26011 gold badges58 silver badges102 bronze badges
2
- how would you like to access the variable later? – Nina Scholz Commented Jul 16, 2018 at 8:06
-
@NinaScholz something like
window["first-name"]
? Not sure though, thats why I asked. – Sandeep Gupta Commented Jul 16, 2018 at 8:08
2 Answers
Reset to default 8You can alias the property name using the colon syntax.
let human = {
"first-name": "John",
"last-name": "Doe",
age: 150
};
let { age, "first-name": firstName } = human;
console.log(age, firstName);
The reason behind the code not working for you is because first-name
is not a valid variable name in Javascript as it considers that as a minus operator rather than hyphen during console.log(first-name)
. So, the fix could be to rename the object property to first_name
and use it elsewhere.
let human= {
"first-name":"John",
"last-name":"Doe",
age:150
}
let {age}= human;
let {'first-name':first_name}= human;
console.log(first_name)