Search code examples
javascriptecmascript-6destructuring

Destructuring objects with hyphenated keys


In my application I'm working with adding some pagination metadata to my store from my response header. One of the keys' names is Per Page which translates to per-page in the object literal.

Is it at all possible to destructure hyphenated keys? I've tried making it into a computed property, camel-casing it, and making it into a plain string but to no avail. Any suggestions?

const { page, [per-page], total } = response.headers;

const { page, perPage, total } = response.headers;

const { page, "per-page", total } = response.headers;

Solution

  • const { page, "per-page": perPage, total } = response.headers;
    

    This will write the value with the key "per-page" into the perPage constant.