DEV Community

Cover image for ⚡ object destructuring in JS: renaming properties⚡
Benjamin Mock
Benjamin Mock

Posted on

5 3

⚡ object destructuring in JS: renaming properties⚡

Want to get better at Web Development 🚀🚀🚀? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/


In the last part of this series, we learned how to destructure objects and access object properties. This time we will see, how to rename properties. Let's do a small recap:

const pastry = {
  name: "waffle",
  sweetness: 80,
  ingredients: ["flour", "butter", "eggs"],
  origin: {
    country: "Greece",
    name: "obelios",
    year: 1200,
  }
};

we can access properties via the dot notation

const name = pastry.name;
console.log(name); // "waffle"

or via destructuring

const { name } = pastry;
console.log(name); // "waffle"

But if we want to choose a name for our variable, we seem to be a bit limited with destructuring. For the dot notation it's easy:

const pastryName = pastry.name;
console.log(pastryName); // waffle

But also while restructuring objects it's possible to freely name the variables via a colon.

const { name: pastryName } = pastry;
console.log(pastryName); // waffle

As you can see there are two name properties: one in the top-level (waffle) and one in the nested origin object (obelios). When we want to destructure both of them, we have to rename at least one of them. Let's do this with the one in the nested origin object.

const { name, origin: { name: originName } } = pastry;
console.log(name); // waffle
console.log(originName); // obelios

Want to get better at Web Development?
🚀🚀🚀subscribe to the Tutorial Tuesday ✉️newsletter

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →