Renaming Destructured Variables

— 2 minute read

I always forget which way round to put the key and the renamed variable so this post is as much for my reference as yours!

When destructuring an object we might want to use a different name for the variable instead of the existing key. This might be because the same name is used already or the key doesn't match your linting rules. We can easily rename it by using the following syntax:

const item = { id: 1, name: 'Stuart' };

const {
id: itemId,
} = item;

console.log(itemId); // 1
console.log(name); // Stuart

Renaming Destructured Variables in Vue.js Templates

If you missed my last post on Destructuring Variables in Vue.js Loops then check it out for how to use destructuring in a v-for loop. You'll be pleased to know we can also use this renaming syntax inside the v-for templates!

<li v-for="{ id: itemId, name } in items" :key="itemId">

Filed under