最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Destructuring object having hyphen in property name - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

You 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)

发布评论

评论列表(0)

  1. 暂无评论